2011-03-21 127 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

显然,你的代码是单向链表