实现单链表的基本运算C#
时间: 2023-10-16 21:11:06 浏览: 144
以下是单链表的基本运算的C#实现:
```csharp
using System;
namespace LinkedListDemo
{
class Program
{
static void Main(string[] args)
{
LinkedList list = new LinkedList();
list.InsertAtEnd(10);
list.InsertAtEnd(20);
list.InsertAtEnd(30);
list.InsertAtEnd(40);
Console.WriteLine("Linked List:");
list.Display();
Console.WriteLine("Length of Linked List: {0}", list.Length());
Console.WriteLine("Deleting element 30 from Linked List");
list.Delete(30);
Console.WriteLine("Linked List after deletion:");
list.Display();
Console.ReadKey();
}
}
class Node
{
public int data;
public Node next;
public Node(int value)
{
data = value;
next = null;
}
}
class LinkedList
{
private Node head;
public LinkedList()
{
head = null;
}
public void InsertAtEnd(int value)
{
Node newNode = new Node(value);
if (head == null)
{
head = newNode;
}
else
{
Node current = head;
while (current.next != null)
{
current = current.next;
}
current.next = newNode;
}
}
public void Delete(int value)
{
if (head == null)
{
return;
}
if (head.data == value)
{
head = head.next;
return;
}
Node current = head;
while (current.next != null)
{
if (current.next.data == value)
{
current.next = current.next.next;
return;
}
current = current.next;
}
}
public int Length()
{
int count = 0;
Node current = head;
while (current != null)
{
count++;
current = current.next;
}
return count;
}
public void Display()
{
Node current = head;
while (current != null)
{
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}
}
```
在主函数中,我们创建一个新的链表对象并插入四个节点。然后,我们打印链表并检查其长度。接下来,我们删除值为30的节点,并再次打印链表以确认节点是否被删除。
链表的节点由Node类表示,它包含一个整型数据和一个指向下一个节点的指针。LinkedList类包含链表的头节点,以及插入,删除,长度和显示链表的方法。
阅读全文