C#实现基础单链表及增删查
链表结点 ListNode
链表 LinkList
//结点结构
class ListNode
{
public object value;
public ListNode next;
//构造空节点
public ListNode()
{
this.value = "Point";
this.next = null;
}
//构造元素节点
public ListNode(object obj)
{
this.value = obj;
this.next = null;
}
~ListNode() {
Console.WriteLine("ByeBye");
}
}
//链表结构
class LinkList
{
//链表“头指针”
public ListNode head;
//链表长度
public int count;
//构造一个带“头指针”的空链表,链表初始化,下一个结点存数据
public LinkList()
{
this.head = new ListNode();
this.count = 0;
}
//获得当前链表长度
public int GetLength()
{
return this.count;
}
//按值查找结点,查找成功返回其位序,查找失败返回0
public int SearchByValue(Object obj)
{
int position = 1;
ListNode currentNode = this.head.next;
while (currentNode.value.Equals(obj) && currentNode != null)
{
currentNode = currentNode.next;
position++;
}
//查找失败
if (currentNode == null)
position = 0;
return position;
}
//按位序查找,查找成功返回第position个结点,查找失败返回null
public ListNode SearchByPosition(int position)
{
if (position > this.count)
return null;
ListNode currentNode = this.head;
for(int i = 0; i < position; i++)
{
currentNode = currentNode.next;
}
return currentNode;
}
//向链表添加结点-头插法
public void AddNodeFromHead(object obj)
{
//新建一个结点
ListNode newNode = new ListNode(obj);
newNode.next = this.head.next;
this.head.next = newNode;
this.count++;
}
//向链表添加结点-尾插法
public void AddNodeFromTail(object obj)
{
ListNode tailNode = SearchByPosition(this.count);
ListNode newNode = new ListNode(obj);
tailNode.next = newNode;
tailNode = newNode;
this.count++;
}
//删除第position个结点
public string DeleteNodeByPosition(int position)
{
if (position > this.count)
return string.Format("删除第{0}个结点失败", position);
ListNode preNode = SearchByPosition(position-1);
//ListNode node = SearchByPosition(position);
this.count--;
preNode.next = preNode.next.next;
return string.Format("删除第{0}个结点成功", position);
}
//删除值为value所有的结点
public void DeleteNodeByValue(object value)
{
ListNode preWorkNode = this.head;
ListNode workNode = preWorkNode.next;
while (workNode != null)
{
if (workNode.value.Equals(value))
{
this.count--;
}
else
{
preWorkNode.next = workNode;
preWorkNode = preWorkNode.next;
}
workNode = workNode.next;
}
if (workNode == null)
{
preWorkNode.next = null;
}
}
//遍历链表
public void Traverse()
{
ListNode currentNode = this.head.next;
while (currentNode != null)
{
Console.Write(currentNode.value + " ");
currentNode = currentNode.next;
}
Console.WriteLine();
}
//反转链表
public LinkList Reverse()
{
ListNode preNode = null;
ListNode currentNode = this.head.next;
ListNode nextNode;
while (currentNode != null)
{
nextNode = currentNode.next;
currentNode.next = preNode;
preNode = currentNode;
currentNode = nextNode;
}
this.head.next = preNode;
return this;
}
}