建立链表
发布网友
发布时间:2022-06-09 03:07
我来回答
共1个回答
热心网友
时间:2022-07-10 18:12
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
typedef int ElemType;
typedef struct LNode {
ElemType date;
struct LNode *next;
}linklist,*link;
void IinitList(link &L)
{
if(L)delete L;
L= (link)malloc(sizeof(LNode)) ;
if (!L) exit(1);
L->next=NULL;
cout<<"链表已经建立\n";
}
int listdelete(link &L,int i,ElemType &e)
{
link p,q; int j;
p=L;j=0;
while(p->next&&j<i-1)
{
p=p->next;++j;
}
q=p->next;
p->next=q->next;
e=q->date;free(q);
cout<<"链表已经删除\n";
return 1;
}
int listinsert(link &L,int i,ElemType e)
{
link p,q;
int j;
p=L;j=0;
while(p&&j<i-1)
{
p=p->next;++j;
}
q= (link)malloc(sizeof(LNode));
q->date=e;
q->next=p->next;
p->next=q; cout<<"链表已经插入\n";
return 1;
}
void show(link l)
{ link p; int j;
p=l;j=0;
cout<<"链表的值为:\n";
while(p->next)
{
cout<<p->next->date<<endl;
p=p->next;
}
}
void destorylinst(link &L)
{
while(L)
{ link p=L;
L=L->next;
free(p) ;
}
L=NULL;
}
void print()
{
cout<<"------------------------\n";
cout<<"------------------------\n";
}
void lookfor(link l,int e)
{
if(l==NULL)
cout<<"链表未建立,请先构造链表\n" ;
else{
link p; int i=0,j=0;
p=l->next;
cout<<"你查找值的位置是:\n " ;
while(p)
{ if(p->date==e)
{ j++;
cout<<i+1<<endl;
}
p=p->next; i++;
}cout<<"查找完毕\n";
if(j==0)
cout<<"你查找的值不在链表中 、\n";
} }
void main()
{ link L=NULL; int k;
while(1)
{
cout<<"按0退出\n"<<"按1建立\n"<<"按2插入\n"<<"按3删除\n"
<<"按4清空链表\n"<<"按5查找\n" ;
print();
int a,i,j;
cin>>a;
switch(a)
{ case 0: if(L!=NULL)
destorylinst(L) ;
exit(1);
case 1:
IinitList(L);
k=0;
print();
show(L) ;
cout<<"空的链表\n";
cout<<"链表长度为: "<<k<<endl;
print();
cout<<"是否要给链表插入值:y----n\n";
char yy;
yy=getchar();
if(yy=='y')
{
cout<<"请输入值!按回车键后输入下一个,结束输入0再按回车\n";
int bb;
cin>>bb;
while(bb!=0)
{ k++;
listinsert(L,k,bb) ;
cin>>bb;
}
print();
show(L) ; cout<<"链表长度为: "<<k<<endl;
}
else break;
print();
break;
case 2:
if(L!=NULL)
{
cout<<"输入位置:\n";
cin>>i;
while(i>k+1 || i<1)
{
cout<<"位置错误,重新输入插入位置\n" ;
cin>>i;
}
cout<<"输入植;\n";
cin>>j;
listinsert(L,i,j) ;
k++;
print();
show(L);
cout<<"链表长度为:"<<k<<endl;
print();
}
else
{ cout<<"链表不存在,请先建链表\n";
print(); }
break;
case 3:
if(L!=NULL)
{
cout<<"输入位置:\n";
cin>>i;
while(i>k || i<1)
{
cout<<"位置错误,重新输入删除位置\n" ;
cin>>i;
}
listdelete (L,i,j);
cout<<"你删除的是:\n";
cout<<j<<endl ;
k--; print();
show(L);
cout<<"链表长度为:"<<k<<endl;
print();
}
else {
cout<<"链表不存在,请先建链表\n";
print();
}
break;
case 4:
destorylinst(L) ;
cout<<"链表已经清空\n";
print();
break;
case 5:
print();
cout<<"输入要查找的值;\n";
int z;
cin>>z;
lookfor(L,z);
print();
break;
default:
break ;
}
}
delete L;
}