使用cSharp语言写循环链表
时间: 2023-08-04 08:05:55 浏览: 48
下面是使用C#语言写循环链表的示例代码:
```csharp
using System;
public class Node {
public int data;
public Node next;
public Node(int data) {
this.data = data;
this.next = null;
}
}
public class CircularLinkedList {
private Node head;
public CircularLinkedList() {
this.head = null;
}
public void AddNode(int data) {
Node newNode = new Node(data);
if (this.head == null) {
newNode.next = newNode;
this.head = newNode;
} else {
Node current = this.head;
while (current.next != this.head) {
current = current.next;
}
current.next = newNode;
newNode.next = this.head;
}
}
public void PrintList() {
if (this.head == null) {
Console.WriteLine("List is empty.");
return;
}
Node current = this.head;
do {
Console.Write(current.data + " ");
current = current.next;
} while (current != this.head);
Console.WriteLine();
}
}
public class Program {
public static void Main(string[] args) {
CircularLinkedList list = new CircularLinkedList();
list.AddNode(1);
list.AddNode(2);
list.AddNode(3);
list.AddNode(4);
list.AddNode(5);
list.PrintList();
}
}
```
在上面的示例代码中,我们定义了一个`Node`类来表示链表中的节点,其中包含一个整数类型的`data`属性和一个指向下一个节点的`next`属性。然后我们定义了一个`CircularLinkedList`类来表示循环链表,其中包含一个指向链表头节点的`head`属性和两个方法:`AddNode`用于向链表中添加新节点,`PrintList`用于打印链表中所有节点的数据。
在`AddNode`方法中,我们先判断链表是否为空,如果是则将新节点作为头节点,同时让其`next`属性指向自己;如果不为空,则找到链表中最后一个节点,将其`next`属性指向新节点,并将新节点的`next`属性指向头节点。
在`PrintList`方法中,我们使用`do-while`循环来遍历链表中所有节点,直到回到头节点为止。在每次循环中,我们打印当前节点的数据,并将`current`指向下一个节点。