2012-12-10 53 views
0

我正在爲學習目的編寫自己的單個鏈接列表,但我堅持「獲取」方法。嘗試獲取單個鏈接列表中元素的值

public void Get(int index) 
{ 
    SLElement curr = _root; 
    SLElement prev = _root._next; 
    for (int i = 0; i <= index; i++) 
    { 
    while (curr._next != null) 
    { 
     if (curr == null) return; 
     prev = curr; 
     curr = curr._next; 
    } 
    } 
    prev._next = curr._next; 
    curr._next = prev; 
    Console.WriteLine("Index {0} has the value {1}", index, curr._value); 
} 

看來工作,但是當我想知道在列表的最後一個元素的值,它給了我一個NullReferenceException 任何辦法阻止呢?

+1

'指數 - 1'是你的最大項目 – Boomer

+0

閱讀從Dr.Dobb的雜誌這個漂亮的一系列關於不對稱界篇http://www.drdobbs.com/cpp/asymmetric-bounds-part-1-what-are-they/240001666 –

回答

2

因爲它從0開始,當​​(即i < index)您for()循環應停止:

for (int i = 0; i < index; i++) 

的第一個元素是在位置0,所以最後一個是在index - 1位置。

1

我得到它的工作現在這個樣子:

public void Get(int index) 
{ 
    SLElement curr = _root; 
    SLElement prev = _root._next; 
    for (int i = 0; i <= index; i++) 
    { 
    while (curr._next != null) 
    { 
     if (curr == null) return; 
     prev = curr; 
     curr = curr._next; 
    } 
    } 
    Console.WriteLine("Index {0} has the value {1}", index, curr._value); 
    if (prev == null) return; 
    prev._next = curr._next; 
    curr._next = _root; 
} 

這對我的作品