1. 程式人生 > >C++寫的帶有頭結點單鏈表建立,插入,刪除,顯示

C++寫的帶有頭結點單鏈表建立,插入,刪除,顯示

#include<iostream>
usingnamespacestd;
structlink
{
chardata;
structlink*next;
};
link*head,*tail;//建立頭指標和尾指標
intcreat();
/******顯示資料*************/
voidshow()
{
link*q=head;
if(head->next==NULL)
{
cout<<"無任何資料,請建立連結串列"<<endl;
creat();
}
else
{
q=q->next;//跳過頭結點
cout<<"show:"
;
do{
cout<<q->data<<"";
q=q->next;
}while(q!=NULL);
cout<<endl;
}
}
/*****帶有頭結點的建立,分為頭插法和尾插法***************/
intcreat()
{
charj;
intm=0;//建立的節點數目
link*p,*q;
q=head;
if(q->next!=NULL)
{
cout<<"已經建立好資料鏈表"<<endl;
return-1;
}
else
{
inti;
cout<<"是插在頭部還是尾部0:頭部;1:尾部
:";
cin>>i;
cout<<"請輸入,以#結束"<<endl;
if(i==1)
{
while(cin>>j,j!='#')
{
p=newlink;//生成新節點
p->data=j;
tail->next=p;//把新節點加到以生成的節點的後面
tail=p;//尾指標指向新生成的節點
m++;
}
tail->next=NULL;//尾節點下一個指向為NULL
}
else
{
tail=NULL;//尾指標為NULL
while(cin>>j,j!='#')
{
p=newlink;//生成新節點
p->data=j;
head->next=p;
p->next=tail;
tail=p;
if(m==0)
q=p;
m++;
}
q->next=NULL;//尾節點下一個指向為NULL
}
returnm;
}
}
/*********刪除指定節點***********/
voiddelelte()
{
link*p=head->next;//P指向第一個節點,跳過頭結點
link*q=head;
charm;
intn=0;
cout<<"請輸入要刪除的節點data:";
cin>>m;
while(p!=NULL)
{
if(m==p->data)
{
q->next=p->next;
p=NULL;
n=1;
break;
}
else
{
p=p->next;
q=q->next;
}
}
if(n==1)
cout<<"刪除完成!"<<endl;
else
cout<<"不存在你要刪除的!"<<endl;
show();
}
/*******插入一個節點************/
voidinsert()
{
link*p=head->next;
intm;
intn=0;
chardata1;
cout<<"請問要插在哪裡?0:表頭;1:某個數後面";
cin>>m;
cout<<"請輸入data";
cin>>data1;
if(m==0)
{
link*q=newlink;
q->data=data1;
head->next=q;
q->next=p;
}
else
{
chardata2;
cout<<"請輸入你要插哪個數後面,請輸入它的data";
cin>>data2;
while(p!=NULL)
{
if(data2==p->data)
{link*f=newlink;
p->next=f;
f->next=p->next;
n=1;
break;
}
else
{
p=p->next;
}
}
if(n==0)
cout<<"不存在你要插的這個數";
}
show();
}
intmain()
{
head=newlink;
head->next=NULL;
tail=head;//尾指標指向頭結點
inti=creat();
if(i!=-1)
{cout<<"建立OK"<<endl;
cout<<"共建立了"<<i<<"個節點"<<endl;
}
show();
delelte();
insert();
return0;
}