Java 如何将这两个链表分别交错?
我正在尝试交错两个列表,以便: 列表1以{a1,a2,a3,a4,a5}开头 列表2以{b1,b2,b3,b4,b5}开头 我希望他们是 {a1,b2,a3,b4,a5} {b1、a2、b3、a4、b5} 这是我的代码:Java 如何将这两个链表分别交错?,java,linked-list,Java,Linked List,我正在尝试交错两个列表,以便: 列表1以{a1,a2,a3,a4,a5}开头 列表2以{b1,b2,b3,b4,b5}开头 我希望他们是 {a1,b2,a3,b4,a5} {b1、a2、b3、a4、b5} 这是我的代码: public void interleave(A3LinkedList other) { A3Node thisCurrent = this.head; A3Node otherCurrent = other.head; int count = 1; w
public void interleave(A3LinkedList other) {
A3Node thisCurrent = this.head;
A3Node otherCurrent = other.head;
int count = 1;
while(count <= this.length){
System.out.println("List1 current at loop "+ count + ": " + thisCurrent); // just to debug
System.out.println("List2 current at loop "+ count + ": " + otherCurrent);
A3Node tempThis = thisCurrent;
A3Node tempOther = otherCurrent;
//if(count%2 == 0){ //if count is even, aka every second object in list
thisCurrent = tempOther; // makes thisCurrent same as otherCurrent
otherCurrent = tempThis; // makes otherCurrent same as temp saved
//}
thisCurrent = thisCurrent.next;
otherCurrent = otherCurrent.next;
count ++;
}
}
测试仪的输出:
{ABCDEFG}
{LMNOPQR}
测试失败:在第203行测试中断
测试失败:testInterleave位于第204行
正如你所看到的,测试仪的输出不是它应该的,它没有通过测试。
为什么?您的代码无法工作,因为您正在方法中创建本地对象引用,并且只重新分配这些本地引用。您需要重新分配引用的成员(即
A3Node.next
)及其指向的内容。例如:
public void interleave(A3LinkedList other) {
A3Node thisCurrent = this.head;
A3Node otherCurrent = other.head;
int count = 1;
while(count <= this.length){
// don't want to lose reference to other's next
A3Node otherNext = otherCurrent.next;
// now we change the references that next are pointing to
// make otherCurrent.next point to thisCurrent.next
otherCurrent.next = thisCurrent.next;
// make thisCurrent.next point to otherNext.next (old otherCurrent.next)
thisCurrent.next = otherNext;
thisCurrent = thisCurrent.next;
otherCurrent = otherCurrent.next;
count += 1;
}
}
public void交错(A3LinkedList-other){
A3Node thisCurrent=this.head;
A3Node otherCurrent=other.head;
整数计数=1;
while(count您的代码不起作用,因为您正在方法中创建本地对象引用,并且只重新分配这些本地引用。您需要重新分配引用的成员(即A3Node.next
)及其指向的对象。如下所示:
public void interleave(A3LinkedList other) {
A3Node thisCurrent = this.head;
A3Node otherCurrent = other.head;
int count = 1;
while(count <= this.length){
// don't want to lose reference to other's next
A3Node otherNext = otherCurrent.next;
// now we change the references that next are pointing to
// make otherCurrent.next point to thisCurrent.next
otherCurrent.next = thisCurrent.next;
// make thisCurrent.next point to otherNext.next (old otherCurrent.next)
thisCurrent.next = otherNext;
thisCurrent = thisCurrent.next;
otherCurrent = otherCurrent.next;
count += 1;
}
}
public void交错(A3LinkedList-other){
A3Node thisCurrent=this.head;
A3Node otherCurrent=other.head;
整数计数=1;
而