链表常用操作
using System;
namespace 链表
{
//一般链表都是有头部节点的 简称为头结点 头结点不参与运算
public class LinkList
{
private Node _head;
private int _count;
public LinkList()
{
_head = new Node();
_count = 0;
}
//添加
public void AddItem(Node newNode)
{
//找到头结点
Node tmpNode = _head;
while (tmpNode.Next != null)
{
tmpNode = tmpNode.Next;
}
tmpNode.Next = newNode;
_count++;
}
//插入
public void InsertItem(int index, Node newnode)
{
if (index<0|index>_count )
{
Console.WriteLine("错误");
}
Node tempNode = _head;
for (int i=0;i <index;i++)
{
tempNode = tempNode.Next;
}
newnode.Next = tempNode.Next;
tempNode.Next = newnode;
_count++;
}
//删除某个
public int RemoveAt(int index)
{
int returnValue = default(int);
if (index<0|index>_count-1 )
{
Console.WriteLine("错误");
goto returnTip;
}
Node tempNode = _head;
for (int i = 0; i < index; i++)
{
tempNode = tempNode.Next;
}
Node deleteNode = tempNode.Next;
tempNode.Next = tempNode.Next.Next;
deleteNode.Next = null;
_count--;
returnTip:
return returnValue;
}
//清空
public void Clear()
{
_head.Next = null;
_count = 0;
}
//遍历
// int --index int --value
public void ShowItem(Action <int ,int >ac)
{
if (_count == 0)
{
Console.WriteLine("空");
return;
}
Node tempNode = _head.Next;
for (int i=0;i <_count;i++ )
{
ac(i,tempNode .Data );
tempNode = tempNode.Next;
}
}
public void daoxu()
{
Node tempnode = _head;
Node shang = null;
Node xia;
tempnode = tempnode.Next;
while (tempnode != null)
{
xia = tempnode.Next;
tempnode.Next = shang;
shang = tempnode;
tempnode = xia;
}
_head.Next = shang;
}
public int GetLength()
{
return _count;
}
}
}
using System;
namespace 链表
{
internal class Program
{
public static void Show(int index,int value)
{
Console.WriteLine(“第{0}个元素是{1}”,index+1,value );
}
public static void Main(string[] args)
{
LinkList linkList = new LinkList();
linkList.AddItem( new Node (1));
linkList.AddItem(new Node(2));
linkList.AddItem(new Node(3));
linkList.AddItem(new Node(4));
linkList.InsertItem(1,new Node (100));
linkList.RemoveAt(3);
linkList.daoxu();
linkList.ShowItem(Show);
// Console.WriteLine(linkList.GetLength());
Console.ReadKey();
}
}
}
namespace 链表
{
public class Node
{
public int Data;
//这个就是地址
public Node Next;
/// <summary>
/// 构造函数目的就是初始化
/// </summary>
public Node()
{
Data = default(int);
Next = null;
}
public Node(int value)
{
Data = value;
Next = null;
}
}
}