0
我寫了一個簡單的方法在環環相扣list.So什麼程序應該理想地做的是結束的時候我給它兩個列表追加兩個鏈接列表
list1 ===>1->2->3
list2 ===>4->5->6
追加一個鏈表updatedList ==>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類,我如何調用該方法從我的主。我知道它有點麻煩,但在這裏它是
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;
}
}
}
該代碼中沒有打印,在無限循環中打印1到6是什麼?你是否也調用過'appendList(list2,list1)'? –
你確定'head1'列表沒有循環引用嗎?我會製作2個列表,每個列表2個,然後遍歷調試器中的代碼,以查看到底發生了什麼以及當current.next指向列表末尾的時候。 –
我做了一個編輯請看看! –