2014-10-31 17 views
0

我正在創建一個單獨鏈接的圓形列表,我似乎無法理解它爲什麼不起作用。這是我的代碼。有人會幫助我,並指出我做錯了什麼?我能夠添加第一個節點,但我不知道如何添加第二個節點。有人可以告訴我如何改變它。我認爲我的名單無休止地遍歷,這就是爲什麼。單鏈式圓形列表添加方法

public class CircularList <E> { 
     private Node<E> head; 

     private class Node <E> 
     { 
      E data; 
      Node <E> next; 

      public Node(E data, Node<E> next) 
      { 
      this.data = data; 
      this.next = next; 
      } 
      public Node(E data) 
      { 
      this.data = data; 
      this.next = null;   
      } 
     }//node 
     public CircularList() 
     { 
      head = null; 

     } 

     public void add(E data) 
     { 
      Node <E> temp = new Node <E> (data); 
      if(head==null) 
      { 
       head=temp; 
       temp.next=temp; 
       System.out.println(head.next.data); 
      } 
      else 
      { 
       Node<E> temp2 = head.next; 
       while(temp2!=head) 
       { 
        if(temp2.next==head) 
        { 
         temp2.next=temp; 
         temp.next=head; 
        } 
        temp2=temp2.next; 
       } 

      } 
     } 
+1

問題是,添加第一個節點後,您會發現head == head.next,這基本上就是您在這段時間所做的檢查。如果不是循環的一部分,只需使用while在最後一個節點中移動,然後在外部添加。 – XecP277 2014-10-31 14:07:57

回答

0
東西線

用這個更新你的其他部分;

  Node<E> temp2 = head; 
      while(temp2.next != head) 
      { 
       temp2=temp2.next; 
      } 
      temp2.next=temp; 
      temp.next=head; 
+0

謝謝。那工作。而且我還必須創建一個remove方法來刪除指定索引處的元素。我不知道該如何處理。 – Koolkirtzz 2014-10-31 14:22:41

+0

與add方法一樣,只計算元素數量,然後刪除該索引處的元素。小心邊緣情況。 – 2014-10-31 14:51:49

0

如果你想使你的單鏈表循環,這將是一個不錯的主意,有一條尾巴,那麼你的代碼可以是沿(僞代碼)

function addElement(data){ 

    Node n = new Node(data) 

    if(list.isEmpty()){ 
     head = n 
     tail = n 
     n.setNext(n) 
    } else { 
     n.setNext(head) 
     tail.setNext(n) 
     head = n 
    } 
}