您的位置:首页 > 编程语言 > C#

用C#基本语句实现的链表算法

2009-08-02 01:00 309 查看
using System;

namespace AlgorithmsLinkList
{
class LinkList //结点类
{
public int data;//数据域(可为任何类型,可以有多个)
public LinkList link;//指针域(引用)

}//end LinkList
class Chain //操作类
{
private LinkList first;//头指针

public Chain()
{
first=null;
}//构造函数
public bool IsEmpty()//判断链表是否为空
{
return first==null;
}//end IsEmpty()
public int Length()//链表的长度
{
LinkList current=first;
int len=0;
while(current!=null)
{
len++;
current=current.link;//指向下一个结点
}
return len;
}//end Length()
public bool Find(int k,int x)//查找第K个元素
{
if(k<1)
{
return false;
}//end if
LinkList current=first;
int index=1;//current的索引
while(index<k && current!=null)
{
current=current.link;//指向下一个结点
index++;
}//end while
if(current!=null)
{
x=current.data;
return true;
}//end if
return false;

}//end Find()
public int Search(int x)//查找元素在那个位置
{
LinkList current=first;
int index=1;
while(current!=null && current.data!=x)
{
current=current.link;
index++;
}//end while
if(current!=null)
{
return index;
}//end if
return 0;
}//end Search()
public void Delete(int k,int x)//删除算法
{
LinkList p=first;
if(k==1) //如果删除的表头
{
first=first.link;
}//end if
else //如果删除的是表的其他位置
{
LinkList q=first;
for(int index=1;index<k-1&&p!=null;index++)
{
q=q.link;
}//end for
p=q.link;
q.link=p.link;
}//end else
x=p.data;

}//end Delete()
public void Insert(int k,int x)//插入算法
{
LinkList p=first;
for(int index=1;index<k && p!=null;index++) //查找插入位置
{
p=p.link;
}//end for
LinkList y=new LinkList(); //创造新结点
y.data=x;
if(k!=0) //如果在P后插入
{
y.link=p.link;
p.link=y;
}//end if
else //作为第一个元素插入
{
y.link=first;
first=y;
}//end else
}//end Insert()
public void Output()//输出链表信息
{
LinkList current;
for(current=first;current!=null;current=current.link)
Console.Write("{0}->",current.data);
Console.WriteLine();
}//end Output()

}//end class Chain
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: