CSharp c循环链表 源代码
时间: 2024-01-23 19:43:09 浏览: 28
以下是C#语言实现循环链表的源代码:
```csharp
using System;
public class CircularLinkedList
{
private class Node
{
public int data;
public Node next;
public Node(int data)
{
this.data = data;
this.next = null;
}
}
private Node head;
private Node tail;
public CircularLinkedList()
{
this.head = null;
this.tail = null;
}
public void AddFirst(int data)
{
Node newNode = new Node(data);
if (head == null)
{
head = newNode;
tail = newNode;
tail.next = head;
}
else
{
newNode.next = head;
head = newNode;
tail.next = head;
}
}
public void AddLast(int data)
{
Node newNode = new Node(data);
if (tail == null)
{
head = newNode;
tail = newNode;
tail.next = head;
}
else
{
tail.next = newNode;
tail = newNode;
tail.next = head;
}
}
public void Delete(int data)
{
Node current = head;
Node previous = null;
if (head == null)
{
return;
}
do
{
if (current.data == data)
{
if (current == head)
{
head = head.next;
tail.next = head;
}
else if (current == tail)
{
previous.next = head;
tail = previous;
}
else
{
previous.next = current.next;
}
return;
}
previous = current;
current = current.next;
} while (current != head);
}
public void Display()
{
Node current = head;
if (head == null)
{
return;
}
do
{
Console.Write(current.data + " ");
current = current.next;
} while (current != head);
Console.WriteLine();
}
}
```
使用示例:
```csharp
CircularLinkedList list = new CircularLinkedList();
list.AddLast(10);
list.AddLast(20);
list.AddLast(30);
list.AddFirst(5);
list.Delete(20);
list.Display(); // 输出:5 10 30
```