单链表的基本操作.docx
- 文档编号:12188956
- 上传时间:2023-04-17
- 格式:DOCX
- 页数:8
- 大小:15.21KB
单链表的基本操作.docx
《单链表的基本操作.docx》由会员分享,可在线阅读,更多相关《单链表的基本操作.docx(8页珍藏版)》请在冰豆网上搜索。
单链表的基本操作
#include
usingnamespacestd;
#definemax9999999
classlist
{
private:
structnode
{
intdate;
node*next;
};
node*first;
public:
list();//无参构造函数,建立只有头结点的空链表
list(inta[],intn);//有参构造函数,建立有n个元素的求链表
~list();
intlen();//求链表的长度
intget(inti);//按位查找。
在单链表中查找第i个结点的元素值
intlocate(intx);//查找元素X
voidinsert(inti,intx);//在第i个位置插入元素x
intDelete(inti);//删除第i个结点
voidprint();
};
list:
:
list()
{
first=newnode;
first->next=NULL;
}
list:
:
list(inta[],intn)
{
first=newnode;
node*r=first;
for(inti=0;i { node*s=newnode; s->date=a[i]; r->next=s; r=s; } r->next=NULL; } intlist: : len() { node*p=first->next; intcount=0; while(p! =NULL) { p=p->next; count++; } returncount; } intlist: : get(inti) { node*p; p=first->next; intcount=1; while(p! =NULL&&count { p=p->next; count++; } if(p==NULL) return0; else returnp->date; } intlist: : locate(intx) { node*p; p=first->next; intcount=1; while(p! =NULL) { if(p->date==x) returncount; p=p->next; count++; } returnmax; } voidlist: : insert(inti,intx) { node*p; p=first; intcount=0; while(p! =NULL&&count { p=p->next; count++; } if(p==NULL) puts("操作异常"); else{ node*s=newnode; s->date=x; s->next=p->next; p->next=s; } } list: : ~list() { while(first! =NULL) { node*q=first; first=first->next; deleteq; } } intlist: : Delete(inti) { node*p=first; intcount=0; while(p! =NULL&&count { p=p->next; count++; } if(p==NULL||p->next==NULL) { cout<<"上溢"< } else{ node*q=p->next; intx=q->date; p->next=q->next; deleteq; returnx; } } voidlist: : print() { node*p=first->next; while(p! =NULL) { cout< p=p->next; } puts(""); } intmain() { inti,n; intx,k=1; cout<<"第1组测试数据请输入n: "; while(cin>>n) { int*a=newint[n]; printf("请输入n个元素: "); for(i=0;i cin>>a[i]; listli(a,n);//有参构造函数,建立有n个元素的求链表 cout<<"长度为: "< cout<<"请输入要查找的位置i: "; cin>>i; { if(li.get(i)==0) puts("查找失败"); else{ cout<<"第"< "< //按位查找。 在单链表中查找第i个结点的元素值 } } cout<<"请输入要查找的元素x: "; cin>>x; if(li.locate(x)==max)//查找元素X puts("查找失败"); else{ cout<<"元素"< "< } puts("请输要插入的位置: i,要插入的元素: x"); cin>>i>>x; if(i<1||i>li.len()+1) cout<<"插入失败"< else{ li.insert(i,x);//在第i个位置插入元素x cout<<"插入后的新链表为: "; li.print(); } cout<<"请输入要删除的结点位置i: "; cin>>i;//删除第i个结点 if(i<1||i>n) puts("操作异常"); else{ cout<<"删除的元素为: "; cout< cout<<"删除后的新链表为: "; li.print(); } li.~list(); cout< system("color1A"); system("pause"); cout<<"第"<<++k<<"组测试数据请输入n: "; } return0; }
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 单链表 基本 操作