2013-08-22 4 views
0

는 내가 그것을 두 목록추가] 두 개의 연결리스트

list1 ===>1->2->3 
list2 ===>4->5->6 

을 줄 때 이상적으로해야 할 프로그램이 무엇인지 list.So 링크 된 다른 사람의 말에 ==>1->2->3->4->5->6

updatedList을 연결 목록을 추가하는 간단한 방법을 썼다

그러나 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; 
} 

아, 그리고 내가 노드 클래스를 추가하는 것을 잊었다 내가 내 주요 .I에서 메소드를 호출하는 방법을 성가신의 비트를 알고 있지만 여기가 문제는 내가이를 이용한이었다

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; 
    } 

} 
} 
+2

무한 루프에서 1부터 6까지 인쇄하는 코드는 인쇄되지 않습니다. 'appendList (list2, list1)'도 호출 했습니까? –

+1

'head1' 목록에 순환 참조가 없다고 확신합니까? 나는 2 개의리스트와 2 개의 아이템을 만들 것이고, 디버거의 코드를 통해 정확히 무슨 일이 일어나는지, 그리고리스트의 끝에있을 때'current.next'가 가리키는 것을 볼 수있을 것이다. –

+0

편집 해주세요. –

답변

0

입니다 순환 참조의 원인이 된 목록. 지금은 잘 작동합니다. 코드를 게시하기 전에 문제가 있다는 것을 알았습니까? 인상적입니다. 고마워요! 새 List2를 만들고 List1과 List2를 전달하여 해결했습니다.

appendList(Node lis1head, Node list2head)