2013-04-11 74 views
0

我正在處理我的OOP類的鏈接列表賦值,並且遇到了一些使用remove方法的問題。我們的教授要求我們寫一個方法:鏈接列表 - 刪除索引處的元素

public Object removeElement(int index) 

這需要一個索引,它是需要移除的元素的位置。它必須返回包含的已刪除節點的數據。但是,我在獲取方法返回正在移除的對象時遇到了問題。出於某種原因,我不斷收到錯誤,該方法必須返回類型對象的結果。我讓它返回一個對象,並且我在各個地方經歷了嘗試和失敗,但都沒有成功。 這裏是我的代碼:

public Object removeElement(int index) 
    { 
    ListIterator iterator = listIterator(); 
    Object object; 
    //If the supplied index is less than zero, throw an exception. 
    if(index < 0) 
    { 
     IndexOutOfBoundsException ex = new IndexOutOfBoundsException(); 
     throw ex; 
    } 

    else 
    { 
     for(int i = 0; i <= index; i++) 
     { 
      if(!iterator.hasNext()) 
      { 
       IndexOutOfBoundsException ex = new IndexOutOfBoundsException(); 
       throw ex; 
      } 
      else 
      { 
       if(i == index) 
       { 
        object = iterator.next(); 
        iterator.remove(); 
        return object; 
       } 
       else 
       { 
        iterator.next(); 

       } 
      } 
     } 
    } 

}

+0

是否錯誤給行號?什麼是完整的錯誤信息? – iamnotmaynard 2013-04-11 20:46:00

+0

錯誤不在編譯,它是在我編譯之前的方法。 – Legare 2013-04-11 20:49:36

+2

@DanielPikul:有效*是*編譯錯誤。這只是你的IDE基本上在你輸入時進行編譯。 – 2013-04-11 20:50:27

回答

3

你擁有了它,如果i == index返回一個對象。但編譯器不知道該循環實際上總是會在那一刻結束。它看着循環的底部,並思考「如果我們到達這裏,我們想要返回什麼?」

我真的調整你的代碼:

if (index < 0) 
{ 
    // No need for a separate variable 
    throw new IndexOutOfBoundsException(); 
} 

// No need for an else block 
ListIterator iterator = listIterator(); 
Object current = null; 
for (int i = 0; i <= index; i++) 
{ 
    // Note: assuming you expose the size(), you could check this up front... 
    if(!iterator.hasNext()) 
    { 
     throw new IndexOutOfBoundsException(); 
    } 
    current = iterator.next(); 
} 
iterator.remove(); 
return current; 

現在你總是呼叫remove並返回當你叫next()給定的次數,因爲這是當環路將結束比通過其他一個例外。

+0

那我該如何解決呢?我有方法拋出一個異常,如果它沒有達到它,我希望這會照顧它。 – Legare 2013-04-11 20:50:48

+0

好的,我比較真的很快。 – Legare 2013-04-11 20:54:05

+0

太棒了!謝謝!!!我實際上保留了我的代碼,並且最初將對象設置爲null,並在循環外寫了一個返回行。你的代碼絕對簡單得多,幫助我思考它。 – Legare 2013-04-11 20:59:00

0

請發佈listIterator()方法實現和您正在獲取的錯誤消息。 注意:>您必須使用類變量(如整數)來管理列表的大小。所以你沒有檢查!iterator.hasNext(),而是將索引與當前大小進行比較。

+0

LinkedLists沒有存儲的大小索引,即ArrayLists。我必須使用hasNext(); – Legare 2013-04-11 20:55:28

+0

LinkedLists沒有大小?什麼是[this](http://docs.oracle.com/javase/6/docs/api/java/util/LinkedList.html#size())呢? – jahroy 2013-04-11 20:57:47

+0

我們不允許在這堂課中使用。我們正在使用由我們的教授編寫的自定義LinkedList子集。我應該澄清一點。 – Legare 2013-04-11 21:00:18

1

首先不要使用java LinkedList中的迭代器,它是Doubly linked list,我想教授想看看你如何實現LikedList數據結構的刪除功能。

其次使循環和條件,其中i+1 == index在這個地方,保存當前的元素像Node returnElement = curent.next;回報,並刪除操作curent.next = curent.next.next;