您的位置:首页 > 汽车 > 时评 > C#中 有内置环形链表吗,如果有请给出使用示例代码

C#中 有内置环形链表吗,如果有请给出使用示例代码

2024/10/5 14:10:11 来源:https://blog.csdn.net/weixin_43542114/article/details/140302965  浏览:    关键词:C#中 有内置环形链表吗,如果有请给出使用示例代码

在C#中,并没有内置的环形链表数据结构,但是可以通过自定义实现来模拟环形链表的功能。一种常见的方法是创建一个环形链表的节点类,并在链表类中实现插入、删除、遍历等操作。

下面是一个简单的示例代码,展示了如何实现一个简单的环形链表:

using System;// 定义环形链表的节点类
public class CircularListNode<T>
{public T Data { get; set; }public CircularListNode<T> Next { get; set; }public CircularListNode(T data){Data = data;Next = null;}
}// 定义环形链表类
public class CircularLinkedList<T>
{private CircularListNode<T> head;private CircularListNode<T> tail;private int count;public CircularLinkedList(){head = null;tail = null;count = 0;}// 插入节点到环形链表末尾public void Add(T data){CircularListNode<T> newNode = new CircularListNode<T>(data);if (head == null){head = newNode;tail = newNode;tail.Next = head; // 形成环}else{tail.Next = newNode;tail = newNode;tail.Next = head; // 更新尾节点的Next指向头节点,形成环}count++;}// 删除指定节点public void Remove(CircularListNode<T> node){if (head == null)throw new Exception("Empty list");CircularListNode<T> current = head;CircularListNode<T> previous = null;do{if (current == node){if (previous != null){previous.Next = current.Next;if (current == tail)tail = previous;}else{head = current.Next;if (head == null)tail = null;elsetail.Next = head; // 更新尾节点的Next指向头节点,保持环形链表}count--;return;}previous = current;current = current.Next;} while (current != head);}// 获取链表长度public int Count{get { return count; }}// 遍历链表并打印节点数据public void Print(){if (head == null)return;CircularListNode<T> current = head;do{Console.Write(current.Data + " ");current = current.Next;} while (current != head);Console.WriteLine();}
}class Program
{static void Main(string[] args){CircularLinkedList<int> circularList = new CircularLinkedList<int>();// 添加节点circularList.Add(1);circularList.Add(2);circularList.Add(3);// 打印链表circularList.Print(); // 输出: 1 2 3// 删除节点CircularListNode<int> nodeToDelete = circularList.head.Next; // 删除第二个节点circularList.Remove(nodeToDelete);// 打印删除后的链表circularList.Print(); // 输出: 1 3}
}

这段代码演示了如何创建一个简单的环形链表类,并实现了基本的插入、删除和遍历操作。请注意,为了形成环形链表,每次在添加新节点或删除节点后,需要更新尾节点的Next指向头节点,以保持链表的环形结构。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com