数据结构 链表类定义代码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
链表类定义:将该类保存在文件LinkList.h中。
//链表类定义:将该类保存在文件LinkList.h中。
template
struct Node
{
T data;
Node
};
template
class LinkList
{
public:
LinkList( )
{
first=new Node
first->next=NULL;
} //建立只有头结点的空链表
LinkList(T a[ ], int n); //建立有n个元素的单链表
~LinkList( ); //析构函数
int Length( ); //求单链表的长度
T Get(int i); //取单链表中第i个结点的元素值
int Locate(T x); //求单链表中值为x的元素序号
void Insert(int i, T x); //在单链表中第i个位置插入元素值为x的结点
T Delete(int i); //在单链表中删除第i个结点
void PrintList( ); //遍历单链表,按序号依次输出各元素
private:
Node
};
template
LinkList
{
Node
while (p) //释放单链表的每一个结点的存储空间
{
Node
p=p->next; //工作指针p指向被释放结点的下一个结点,使单链表不断开
delete q;
}
}
template
T LinkList
{
Node
p=first->next; j=1; //或p=first; j=0;
while (p && j
{
p=p->next; //工作指针p后移
j++;
}
if (!p) throw "位置";
else return p->data;
}
template
void LinkList
{
Node
p=first ; j=0; //工作指针p初始化
while (p && j { p=p->next; //工作指针p后移 j++; } if (!p) throw "位置"; else { Node s=new Node s->data=x; //向内存申请一个结点s,其数据域为x s->next=p->next; //将结点s插入到结点p之后 p->next=s; } } template T LinkList { Node p=first ; j=0; //工作指针p初始化 while (p && j { p=p->next; j++; } if (!p || !p->next) throw "位置"; //结点p不存在或结点p的后继结点不存在 else { Node q=p->next; x=q->data; //暂存被删结点 p->next=q->next; //摘链 delete q; return x; } } template LinkList { first=new Node first->next=NULL; //初始化一个空链表 for (int i=0; i { Node s->data=a[i]; //为每个数组元素建立一个结点 s->next=first->next; //插入到头结点之后 first->next=s; } } template void LinkList { Node p=first->next; while (p) { cout< p=p->next; } } #include #include"LinkList.h" void main( ) { int r[ ]={10,9,8,7,6,5,4,3,2,1}; LinkList cout<<"原表为:"< a.PrintList(); cout< a.Insert(1,-2); //执行插入操作; a.Insert(2,-1); a.Insert(3,0 ); cout<<"执行插入后输出为:"< a.PrintList(); cout< a.Delete(0); a.Delete(-1);