2013-06-19 75 views
3

打印後firstnode地址打印last node地址,所以如果我想顯示我的 Linked List所以我該怎麼辦?鏈接列表重複後去最後一個節點在顯示

請給出有效的解決方案

public class LLink { 
    public Link first, last, tmp; 

    public void add(int data) { 
     Link newLink = new Link(data); 
     if (first == null) { 
      first = newLink; 
      System.out.println(first.data); 
      System.out.println(newLink); 
     } else { 
      first.next = newLink; 
      // first=newLink; 
      System.out.println(newLink.data); 
      // newLink = newLink.next; 
      // newLink.next=newLink; 
      last = newLink; 

     } 
     // newLink.next=first;//it copies the address of old first 
     // last=newLink; 
     System.out.println("end"); 
     System.out.println(last); 
    } 

    public void delete() { 
     Link tmp = first; 
     first = first.next; 
     System.out.println(first.data); 

    } 

    public void display() { 
     System.out.println("display"); 
     Link e = first; 
     while (e != null) { 
      System.out.println(e.data); 
      System.out.println(e); 
      System.out.println("first-next" + first.next); 
      System.out.println(e.next); 
      e = e.next; 
     } 

    } 

    class Link { 
     public int data; 
     public Link next; 

     public Link(int data) { 
      this.data = data; 
     } 

    } 
} 
+0

我們看一些輸入和輸出。你如何運行代碼? –

+1

後樣本I/O – Kishore

+0

現在它一直在正常工作。 – Sheel

回答

1

。在你的附加功能,不是你的顯示功能的問題。

public void add(int data) { 
    Link newLink = new Link(data); 
    if (first == null) { 
     first = newLink; 
     System.out.println(first.data); 
     System.out.println(newLink); 
    } else { 
     first.next = newLink; // <-- This is wrong 
     // first=newLink; 
     System.out.println(newLink.data); 
     // newLink = newLink.next; 
     // newLink.next=newLink; 
     last = newLink; 

    } 
    // newLink.next=first;//it copies the address of old first 
    // last=newLink; 
    System.out.println("end"); 
    System.out.println(last); 
} 

添加到鏈表時,應該添加到最後一個節點,而不是更改第一個節點的下一個指針。您已經有效地創建了一個雙節點列表,每次添加節點時都會更改最後一個節點。

相反,你應該有類似:

public void add(int data) { 
    Link newLink = new Link(data); 
    if (first == null) { 
     first = last = newLink; 
    } else { 
     last.next = newLink; // First set the next pointer of the last node to the new node 
     last = newLink; // Once the pointer is set, now set last node properly 
    } 
} 
相關問題