namespace Testmain
{
public class TwoWayNode
{
public TwoWayNode preNode;
public int Data;
public TwoWayNode nextNode;
public TwoWayNode(int data)
{
preNode = null;
this.Data = data;
nextNode = null;
}
}
}
2.使用DoubleLinkedLists类创建链表,包含添加、展示、删除、插入
namespace Testmain
{
public class DoubleLinkedLists
{
private TwoWayNode head;
public void AddNode(int data)
{
TwoWayNode newNode = new TwoWayNode(data);
if (head == null)
{
head = newNode;
}
else
{
TwoWayNode currentNode = head;
while (currentNode.nextNode != null)
{
currentNode = currentNode.nextNode;
}
currentNode.nextNode = newNode;
newNode.preNode = currentNode;
}
}
public void delectNode(int data)
{
if (head == null)
{
return; // 空链表
}
if (head.Data == data)
{
head = head.nextNode; // 如果要删除的节点在头部
return;
}
TwoWayNode current = head;
while (current.nextNode != null)
{
if (current.nextNode.Data == data)
{
current.nextNode = current.nextNode.nextNode;
current.nextNode.nextNode.preNode = current;
return;
}
current = current.nextNode;
}
}
public void InsertNode(int index, TwoWayNode setNode)
{
if (index < 0)
{
throw new ArgumentOutOfRangeException("index", "Index cannot be negative");
}
if (index == 0)
{
setNode.nextNode = head;
if (head != null)
{
head.preNode = setNode;
}
head = setNode;
return;
}
TwoWayNode current = head;
int count = 0;
while (current != null && count < index - 1)
{
current = current.nextNode;
count++;
}
if (current == null)
{
throw new ArgumentOutOfRangeException("index", "Index is greater than the number of nodes in the list");
}
setNode.nextNode = current.nextNode;
if (current.nextNode != null)
{
current.nextNode.preNode = setNode;
}
current.nextNode = setNode;
setNode.preNode = current;
}
public void printList()
{
TwoWayNode current = head;
while (current.nextNode != null)
{
Console.Write(current.Data + "-");
current = current.nextNode;
}
Console.WriteLine(current.Data);
}
}
}
3、程序入口
using System;
namespace Testmain
{
class Program
{
static void Main(string[] args)
{
DoubleLinkedLists node = new DoubleLinkedLists();
node.AddNode(1);
node.AddNode(2);
node.AddNode(3);
node.AddNode(4);
node.AddNode(5);
node.AddNode(6);
node.delectNode(3);
TwoWayNode node1 = new TwoWayNode(27);
node.InsertNode(0, node1);
node.printList();
}
}
}