如何用C#构建双向链表

   2024-09-30 4770
核心提示:在C#中,要创建一个双向链表,首先需要定义一个表示链表节点的类,其中包含指向前一个和后一个节点的引用public class NodeT{pub

在C#中,要创建一个双向链表,首先需要定义一个表示链表节点的类,其中包含指向前一个和后一个节点的引用

public class Node<T>{    public T Data { get; set; }    public Node<T> Previous { get; set; }    public Node<T> Next { get; set; }    public Node(T data)    {        Data = data;        Previous = null;        Next = null;    }}public class DoublyLinkedList<T>{    private Node<T> _head;    private Node<T> _tail;    public DoublyLinkedList()    {        _head = null;        _tail = null;    }    // 在链表末尾添加新节点    public void Add(T data)    {        var newNode = new Node<T>(data);        if (_head == null)        {            _head = newNode;            _tail = newNode;        }        else        {            newNode.Previous = _tail;            _tail.Next = newNode;            _tail = newNode;        }    }    // 从链表中删除节点    public bool Remove(T data)    {        var current = _head;        while (current != null)        {            if (current.Data.Equals(data))            {                if (current.Previous != null)                    current.Previous.Next = current.Next;                else                    _head = current.Next;                if (current.Next != null)                    current.Next.Previous = current.Previous;                else                    _tail = current.Previous;                return true;            }            current = current.Next;        }        return false;    }    // 打印链表中的所有元素    public void Print()    {        var current = _head;        while (current != null)        {            Console.Write(current.Data + " ");            current = current.Next;        }        Console.WriteLine();    }}

以下是如何使用这个双向链表类的示例:

class Program{    static void Main(string[] args)    {        var list = new DoublyLinkedList<int>();        list.Add(1);        list.Add(2);        list.Add(3);        list.Print(); // 输出: 1 2 3        list.Remove(2);        list.Print(); // 输出: 1 3    }}

这个实现提供了基本的双向链表功能,包括添加、删除和打印链表中的元素。你可以根据需要扩展此实现,例如添加更多的遍历方法或者实现链表的其他操作。

 
举报打赏
 
更多>同类网点查询
推荐图文
推荐网点查询
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号