我写了一个简单的方法,在另一个链表的末尾附加一个链表。因此,该程序理想情况下应该做的是,当我给它两个列表
list1 ===>1->2->3
list2 ===>4->5->6
更新列表==>1->2->3->4->5->6
但当我运行方法appendList
时,它会进入无限循环,无限期地打印1到6。我在这里做错了什么?
public static Node appendList(Node head1, Node head2) {
Node prev = null;
Node current = head1;
while (current != null) {
prev = current;
current = current.next;
}
prev.next = head2;
return head1;
}
哦,我忘了添加Node类以及如何从main中调用该方法。我知道它有点麻烦,但这里是
public class ReverseLinkedList {
class Node {
int data;
Node next;
Node(int data) {
this.data = data;
}
public void displayData() {
System.out.println(data);
}
}
public static void main(String args[]) {
ReverseLinkedList reversedList = new ReverseLinkedList();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the length of the linked list!!");
int listSize = scanner.nextInt();
System.out.println("Enter the Numbers you want to insert!!");
int count = 0;
while (scanner.hasNextLine()) {
if (count == listSize)
break;
reversedList.insert(scanner.nextInt());
count++;
}
System.out.println("Inserted List !!");
reversedList.displayList();
/*
* Node reverseNodeStart =
* reversedList.reverseList1(reversedList.first);
* System.out.println("Reversed List !!"); while (reverseNodeStart !=
* null) { reverseNodeStart.displayData(); reverseNodeStart =
* reverseNodeStart.next; }
*/
Node reverseNodeStart = reversedList.appendList(reversedList.first,
reversedList.first);
while (reverseNodeStart != null) {
reverseNodeStart.displayData();
reverseNodeStart = reverseNodeStart.next;
}
}
}
问题是我使用的是导致循环引用的相同列表。它现在运行良好。你甚至在我发布代码之前就知道这个问题了,这真是令人印象深刻。谢谢我通过创建一个新的List2并传入List1和List2来解决这个问题。
appendList(Node lis1head, Node list2head)