附加两个链表

时间:2013-08-22 23:35:51

标签: java algorithm data-structures linked-list

我写了一个简单的方法来在另一个链表的末尾追加一个链表。那么理想的程序应该是什么时候我给它两个列表

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 个答案:

答案 0 :(得分:0)

问题是我使用的是导致循环引用的相同List。现在工作正常。即使在我发布代码之前,你也知道这个问题令人印象深刻。谢谢!!我通过创建一个新的List2并传入List1和List2来解决它。

  appendList(Node lis1head, Node list2head)