雙向鏈表的定義以及常用的操作
namespace DounlyLinkedlist
...{
//定義雙向鏈表的結點
public class Node
...{
public Object Element;
public Node FLink;
public Node BLink;
public Node()
...{
Element = null;
FLink = null;
BLink = null;
}
public Node(Object element)
...{
Element = element;
&n FLink = null;
BLink = null;
}
}
//鏈表操作的類
public class LinkedList
...{
public Node Header;
public LinkedList()
...{
Header = new Node("Header");
Header.FLink = null;
Header.BLink = null;
}
//查找結點
private Node Find(Object item)
...{
Node Current = new Node();
Current = Header;
while (Current.Element != item)
...{
Current = Current.FLink;
}
return Current;
}
//插入結點
public void InsertNode(Object item,Object postionItem)
...{
Node Current = new Node();
Node NewItem = new Node(item);
Current = Find(postionItem);
if (Current != null)
...{
NewItem.FLink = Current.FLink;
NewItem.BLink = Current;
Current.FLink = NewItem;
}
}
//刪除結點
public void Remove(Object item)
...{
Node P = Find(item);
if (P.FLink != null)
...{
P.BLink.FLink = P.FLink;
P.FLink.BLink = P.BLink;
P.BLink = null;
P.FLink = null;
}
}
//查找雙向鏈表最後一個結點元素
private Node FindLast()
...{
Node Current = new Node();
Current = Header;
& while (!(Current.FLink == null))
...{
Current = Current.FLink;
}
return Current;
}
//逆向打印雙向鏈表
public void PrintReverse()
...{
Node Current = new Node();
Current = FindLast();
while (!(Current.BLink == null))
...{
Console.WriteLine(Current.Element);
Current = Current.BLink;
}
}
//打印雙向鏈表
public void Print()
...{
Node Current = new Node();
Current = Header;
while (!(Current.FLink == null))
...{
Console.WriteLine(Current.FLink.Element);
Current = Current.FLink;
}
}
}
}
具體調用代碼:
static void Main(string[] args)
...{
DounlyLinkedlist.Node FirstNode = new DounlyLinkedlist.Node("Tommy");
DounlyLinkedlist.Node SecondNode = new DounlyLinkedlist.Node("Wei");
DounlyLinkedlist.Node ThirdNode = new DounlyLinkedlist.Node("Chencaixia");
DounlyLinkedlist.Node FourthNode = new DounlyLinkedlist.Node("weiwei");
DounlyLinkedlist.LinkedList MyDoublrLink = new DounlyLinkedlist.LinkedList();
MyDoublrLink.Header.FLink = FirstNode;
MyDoublrLink.Header.BLink = null;
FirstNode.FLink = SecondNode;
FirstNode.BLink = MyDoublrLink.Header;
SecondNode.FLink = ThirdNode;
SecondNode.BLink = FirstNode;
ThirdNode.FLink = FourthNode;
ThirdNode.BLink = SecondNode;
FourthNode.BLink = ThirdNode;
FourthNode.FLink = null;
MyDoublrLink.InsertNode("test", "Chencaixia");
MyDoublrLink.Remove("Wei");
MyDoublrLink.Print();
Console.ReadLine();
}