CShap 双向链表 源代码
时间: 2023-09-30 20:11:41 浏览: 77
双向链表源码
以下是C#双向链表的源代码示例:
```
using System;
class Node {
public int data;
public Node next;
public Node prev;
public Node(int d) {
data = d;
next = null;
prev = null;
}
}
class DoublyLinkedList {
private Node head;
public DoublyLinkedList() {
head = null;
}
public void Add(int d) {
Node newNode = new Node(d);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.prev = current;
}
public void Remove(int d) {
if (head == null) {
return;
}
Node current = head;
while (current != null) {
if (current.data == d) {
if (current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
}
return;
}
current = current.next;
}
}
public void Print() {
Node current = head;
while (current != null) {
Console.Write(current.data + " ");
current = current.next;
}
Console.WriteLine();
}
}
class Program {
static void Main(string[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.Add(1);
list.Add(2);
list.Add(3);
list.Add(4);
list.Add(5);
list.Print();
list.Remove(3);
list.Print();
}
}
```
阅读全文