帮助c#中的链接列表

时间:2011-03-21 19:01:28

标签: c# linked-list

我如何知道此代码是否来自单一链接列表?

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;
    }
}
}

由于

2 个答案:

答案 0 :(得分: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;
}

并向List类添加tail。操作列表时,请务必正确链接到上一项。然后add方法变为:

// 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;
}

您现在可以在两个方向上遍历您的列表。最后添加项目的效果更好,因为您不必遍历整个列表来获取尾部项目。

答案 1 :(得分:0)

单链接列表包含具有数据字段和下一个字段的节点,该字段指向链接列表中的下一个节点。

双向链接列表中,除了下一节点链接之外,每个节点还包含指向序列中前一个节点的第二个链接字段。这两个链接可以被称为前向和后向,或者下一个和前一个(即)。

doubly-linked list

显然你的代码是单链表