2015-04-25 42 views
1

我的插入方法說明: 我分配了尾部的「下一個變量」來保存舊節點的地址。我將尾部插入新列表中。無法正確顯示列表中的節點從尾部到頭部正確

我試圖顯示列表從尾部開始,並通過列表,直到它到達頭部。

問題: 但輸入顯示C這不是我想要的。顯示方法應該顯示C,B,A。

我甚至在紙上調試我的代碼。我不知道爲什麼顯示不檢索鏈接列表中鏈接節點的最後一個地址。它只檢索列表中的最後一個節點,並只顯示列表中的最後一個節點。

public static void main(String[] args) 
    { 
     LinkedList list = new LinkedList(); 
     list.insert("A"); 
     list.insert("B"); 
     list.insert("C"); 
     list.display(); 

    } 

public void insert(String data) 
    { 
     Link link = new Link(data); 

     // this code only executes the first time when the list has 
     // no node 
     if(head == null) 
     { 
      head = link; 
      tail= link; 
     } 
     // this code will execute when the linked list has one or more node         
     else 
     { 
      tail.next = tail; 
      tail = link; 

     } 
    } 

    public void display() 
    { 

     while(tail != null) 
     { 
      System.out.println(tail.data); 
      tail = tail.next; 

     } 

    } 
+2

不應該是tail.next = link,tail = tail.next?你擁有它的方式是tail.next = tail,它將指向相同的音符並創建一個循環。 –

+0

我測試了您的代碼,但鏈接列表仍顯示「C.」。 「display」中的 – Nicholas

+2

是否迭代列表中的項目?它看起來像你只是打印尾巴。鏈表中的第一個節點是頭。 – Paxic

回答

1

您已經創建了一個單獨鏈接列表。該名單有一個頭部和尾部,鏈接從頭到尾。一個單一的鏈接列表設計有一個方向「前進」。對於元素[a,b,c],列表鏈接a-> b-> c。要以相反順序打印元素,至少有兩個選項。使用遞歸打印元素c,b,a或實現doubly linked list

+1

你可以改變你的結構是「顛倒」,並有一個尾巴的方向,但帽子不會是可取的 - 它違背了穀物,預期的行爲是頭尾。 – Paxic

+1

所以單鏈表只能從「頭到尾」遍歷。但雙重聯繫,你可以從「頭到尾」和「尾巴到頭」進行遍歷。 – Nicholas