2014-10-16 20 views
0

我如何將我的添加和刪除方法從正常鏈接轉換爲循環鏈接列表。使用這段代碼,我想我需要一個尾部引用等等?圓形列表添加和刪除方法

public void add(int index, Object item) 
        throws ListIndexOutOfBoundsException { 


    //our index needs to go in along with our stuff in item 
     Node temp = new Node(item); 
     Node current = head; 

     for(int i = 1; i < index && current.getNext() != null; i++) 
     { 
      current = current.getNext(); 
     } 
     // set the new node's next-node reference to this node's next-node reference 
     temp.setNext(current.getNext()); 
     // now set this node's next-node reference to the new node 
     current.setNext(temp); 
    // current.setPrevious(); 
     numItems++;// increment the number of elements variable 

    } 

    public boolean remove(int index) 
        throws ListIndexOutOfBoundsException { 

     if(index < 1 || index > size()) 
      return false; 

     Node current = head; 
     for(int i = 1; i < index; i++) 
     { 
      if(current.getNext() == null) 
       return false; 

      current = current.getNext(); 
     } 
     current.setNext(current.getNext().getNext()); 
     numItems--; // decrement the number of elements variable 
     return true; 


    } // end remove 

回答

0

在循環鏈表,current.getNext()不會null。您必須以另一種方式檢查何時到達列表末尾(current.getNext() == null將始終爲false)。

第一個選項是與頭節點比較,即如果current.getNext() == head,那麼current是列表中的最後一個元素,你可以停止。

但是,既然你指望索引,你也可以確保索引總是在0到size()之間(你目前在你的刪除方法中做的)。