2011-03-21 93 views
0

我怎樣才能知道這個代碼是從單鏈接列表?幫助鏈接列表中的c#

namespace ConsoleApplication1 
{ 

// T is the type of data stored in a particular instance of GenericList. 
public class GenericList<T> 
{ 
    private class Node 
    { 
     // Each node has a reference to the next node in the list. 
     public Node Next; 
     // Each node holds a value of type T. 
     public T Data; 
    } 

    // The list is initially empty. 
    private Node head = null; 

    // Add a node at the beginning of the list with t as its data value. 
    public void AddNode(T t) 
    { 
     Node newNode = new Node(); 
     newNode.Next = head; 
     newNode.Data = t; 
     head = newNode; 
    } 

    // The following method returns the data value stored in the last node in 
    // the list. If the list is empty, the default value for type T is 
    // returned. 
    public T GetFirstAdded() 
    { 
     // The value of temp is returned as the value of the method. 
     // The following declaration initializes temp to the appropriate 
     // default value for type T. The default value is returned if the 
     // list is empty. 
     T temp = default(T); 

     Node current = head; 
     while (current != null) 
     { 
      temp = current.Data; 
      current = current.Next; 
     } 
     return temp; 
    } 
} 
} 

感謝

+0

對不起 - 不知道你在問什麼! – Stuart 2011-03-21 19:03:07

回答

4

每個節點包含一個鏈接到列表中的下一個節點。這就是爲什麼它被稱爲鏈接名單。

private class Node 
{ 
    // Each node has a reference to the next node in the list. 
    public Node Next; 
    // Each node holds a value of type T. 
    public T Data; 
} 

這是一個單鏈表列表中,因爲沒有Previous(沒有tail)。所以這個列表只能在一個方向上遍歷。爲了使雙聯名單,你會做這樣的事情:

private class Node 
{ 
    // Each node has a reference to the next node in the list. 
    public Node Next; 
    // Each node has a reference to the previous node in the list. 
    public Node Previous; 
    // Each node holds a value of type T. 
    public T Data; 
} 

,並添加一個tail到List類。在列表上操作時,請確保正確鏈接到前一個項目。然後添加方法變爲:

// Add a node at the beginning of the list with t as its data value. 
public void AddNode(T t) 
{ 
    Node newNode = new Node(); 
    newNode.Next = head; 
    if (head != null) { 
     head.Previous = newNode; 
    } 
    newNode.Data = t; 
    head = newNode; 
} 

您現在可以在兩個方向上遍歷您的列表。並且在最後添加項目會更好,因爲您不必遍歷整個列表即可查看尾部項目。

+0

那麼鏈表是不是? 謝謝 – 2011-03-21 19:04:27

+1

是的,它是一個鏈接列表,因爲每個項目都包含到下一個項目的鏈接。這是一個單鏈表,因爲只有一個方向的鏈接。我誤解了你的問題。 – Jan 2011-03-21 19:08:06

0

單鏈接列表包含具有數據字段以及下一個字段的節點,該字段指向鏈接列表中的下一個節點。

雙鏈接列表中,除了下一個節點鏈接,每個節點還包含指向序列中前一個節點的第二個鏈接字段。這兩個鏈接可能被稱爲向前和向後,或者next和prev(ious)。

doubly-linked list

顯然,你的代碼是單向鏈表