您的位置:首页 > 理论基础 > 计算机网络

转贴-- 单向链表的实现 C# http://blog.csdn.net/a497785609/archive/2009/09/29/4617692.aspx

2009-12-13 16:46 513 查看
转贴-- 单向链表的实现 C# http://blog.csdn.net/a497785609/archive/2009/09/29/4617692.aspx

using System ;
public class LinkedList
{
//嵌套类表示单个节点;
private class Node
{
public Node (object values)
{
item=values ;
}
public object item; //数据域;
public LinkedList.Node next;//指针域;
public override string ToString()
{
return item.ToString ();
}
}
private int count;//记录元素个数;
public int Count
{
get {return this.count ;}
}
private Node head;//头指针;
public object this[int index]//索引器;
{
get {return GetByIndex (index).item;}
set{GetByIndex (index).item=value ;}
}

//①添加元素;
public void Add(object values)
{
Node newNode=new Node (values);
if(head ==null ) //如果头指针为空;
{
head =newNode ;
}
else
{
GetByIndex(count-1).next=newNode; //插到链表结尾;
}
count ++; //链表长度+1;
}

//②在指定索引处插入元素;
public void Insert(int index,object values)
{
Node tempNode;
if(index ==0)
{
if(head ==null )
{
tempNode =new Node (values );
tempNode.next =head ;
head =tempNode ;
}
}
else
{
Node preNode=GetByIndex(index-1); //找插入节点的前驱;
Node nextNode=preNode.next ; //找插入节点的后继结点;
tempNode =new Node (values);
preNode.next =tempNode;
tempNode.next =nextNode ;
}
count ++;
}

//③删除指定索引元素;
public void RemoveAt(int index)
{
if (index ==0) //删除节点为头指针;
{
head =head.next ;
}
else
{
Node preNode=GetByIndex(index-1);
if(preNode.next ==null)
{
throw new ArgumentOutOfRangeException("index","索引超出范围!");
}
preNode.next =preNode.next.next ;
}
count --;
}

public override string ToString()
{
string s="";
for(Node temp=head; temp!=null; temp=temp.next)
{
s+=temp.ToString ()+" ";
}
return s;
}

private Node GetByIndex(int index)
{
if((index <0)||(index >= this.count ))
{
throw new ArgumentOutOfRangeException("index","索引超出范围!");
}
Node tempNode=this.head ;
for(int i=0;i<index ;i++)
{
tempNode=tempNode.next ;
}
return tempNode ;
}
}
class App
{
static void Main()
{
LinkedList lst=new LinkedList ();
Console .WriteLine("①添加元素:");
lst .Add (0);
lst .Add (1);
lst .Add (2);
lst .Add (3);
Console .WriteLine(lst.ToString());

Console .WriteLine("②在2号位置,添加元素50:");
lst .Insert (2,50);

Console .WriteLine(lst.ToString());

Console .WriteLine("③移除1号元素:");
lst.RemoveAt(1);
Console .WriteLine(lst.ToString());

Console .WriteLine("④把2号元素赋值为9:");
lst [2]=9;
Console .WriteLine(lst.ToString());
}
}

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/a497785609/archive/2009/09/29/4617692.aspx
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐