c#链表创建的方法是什么

   2024-10-28 6310
核心提示:在C#中创建链表有两种方法:使用LinkedList类:这是C#内置的链表实现,可以直接使用。首先需要引入System.Collections.Generic命

在C#中创建链表有两种方法:

使用LinkedList类:这是C#内置的链表实现,可以直接使用。首先需要引入System.Collections.Generic命名空间,然后可以通过以下代码创建一个链表:
using System;using System.Collections.Generic;class Program{    static void Main()    {        LinkedList<int> linkedList = new LinkedList<int>();        linkedList.AddLast(1);        linkedList.AddLast(2);        linkedList.AddLast(3);                foreach (var item in linkedList)        {            Console.WriteLine(item);        }    }}
自定义链表类:也可以自定义链表类来实现链表的功能。例如,可以创建一个Node类和LinkedList类来表示链表节点和链表本身:
using System;class Node{    public int data;    public Node next;    public Node(int data)    {        this.data = data;        this.next = null;    }}class LinkedList{    public Node head;    public void Add(int data)    {        Node newNode = new Node(data);        if (head == null)        {            head = newNode;        }        else        {            Node current = head;            while (current.next != null)            {                current = current.next;            }            current.next = newNode;        }    }    public void Display()    {        Node current = head;        while (current != null)        {            Console.WriteLine(current.data);            current = current.next;        }    }}class Program{    static void Main()    {        LinkedList linkedList = new LinkedList();        linkedList.Add(1);        linkedList.Add(2);        linkedList.Add(3);                linkedList.Display();    }}

无论采用哪种方法,都可以通过添加节点、删除节点等操作来操作链表。

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

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