?? 循環鏈表.cpp
字號:
#include<iostream.h>
typedef struct LNode //循環鏈表的存儲結構
{
int data;
struct LNode *next;
}LNode, *LinkList;
int ListLocate_L(LinkList L,int x) //在帶頭結點的循環鏈表L中查找與x相等的所有元素的位序
{int i,count=0; LinkList p;
p=L->next; i=1; //i的初值為第一個元素的位序
//p的初值為第一個結點的位序
cout<<"請輸入您想要查找的整數元素的值:"<<endl;
cin>>x;
while(p!=L&&p->data!=x) //尋找數據域的值為x的結點
{p=p->next; i++;}
if(p==L){cout<<"Not Found!"<<endl;} //沒有找到,顯示NOT FOUND
else
{for(p;p!=L;p=p->next) //從找到的第一個滿足要求的結點起,繼續往后進行尋找滿足要求的其他結點
if(p->data==x)
{cout<<"您要查找的元素存在!它在鏈表中的位置是:"<<i<<endl<<endl<<endl;
i++;count++;}
else i++;
cout<<"您查找到的滿足要求的元素一共有"<<count<<"個"<<endl<<endl<<endl;
}//所有與x相等的元素都已經找到,顯示其所有結點所在的鏈表中的位置
return L,x;
}
int ListInsert_L(LinkList &L,int i,int e) //在帶頭結點的循環鏈表L中第i個位置之前插入元素e
{LinkList p,s;
p=L; int j=0; //P的初值為頭結點
//j的初值為0
cout<<"請輸入您想要插入的整數元素:";
cin>>e;
cout<<"請輸入您想要插入的位置";
cin>>i;
while(p->next!=L&&j<i-1){p=p->next;++j;} //尋找第i-1個結點
if(p->next==L||j>i-1) //i小于1或者大于表長+1
{cout<<"插入的位置不合適,請重新輸入";}
else
{ s=(LinkList)new int(sizeof(LNode)); //生成新結點
s->data=e; s->next=p->next; //插入L中
p->next=s;
cout<<"經插入后現在鏈表中的元素為:";
for(p=L->next;p!=L;p=p->next) //顯示插入完畢后的循環鏈表
cout<<p->data<<" ";}
cout<<endl<<endl<<endl;
return L,i,e;}
int ListDelete_L(LinkList &L, int i, int &e) //在帶頭結點的循環鏈表L中,刪除第i個元素,并由e返回其值
{LinkList p,q; int j=0;
p=L;
cout<<"請輸入您想要刪除的元素的位置:";
cin>>i;
while(p->next!=L&&j<i-1) //尋找第i個結點,并令p指向其前驅
{p=p->next; ++j;}
if(p->next==L||j>i-1)
cout<<"您輸入的位置有誤,請重新輸入"; //刪除的位置不合理
else
{q=p->next; p->next=q->next; e=q->data; delete (p); //刪除并釋放結點
cout<<"刪除已經完成!現在鏈表中的元素為:";
for(p=L->next;p!=L;p=p->next)
cout<<p->data<<" ";} //顯示刪除完畢后的循環鏈表
cout<<endl<<endl<<endl;
return L,i,e;
}
main() //順位序輸入10個元素,建立帶表頭結點的循環鏈表L
{LinkList L;
LinkList p;
LinkList q;
int x,e;
L=(LinkList)new int(sizeof(LNode)); //先建立一個帶頭結點的循環鏈表
L->next=L;
q=L;
cout<<"請輸入任意10個整數:"<<endl;
for(int i=0;i<10;i++)
{p=(LinkList)new int(sizeof(LNode)); //生成10個新結點
cin>>p->data; //輸入元素的值
p->next=q->next; //插入結點
q->next=p;
q=p;}
cout<<"循環鏈表已建立成功,鏈表中目前10個整數分別為:"<<endl; //輸出建立成功后的循環鏈表
for(p=L->next;p!=L;p=p->next)
{cout<<p->data<<" ";}
cout<<endl;
while(p->next!=L) //P的下一個結點不為頭結點L時,可執行下列操作
{cout<<"請輸入數字1、2、3、4四個數字執行您想要的操作"<<endl<<"1、查找"<<endl<<"2、插入"<<endl<<"3、刪除"<<endl<<"4、不需要再進行操作,退出程序"<<endl;
cout<<"請選擇:";
int n;
cin>>n;
if(n==1)
ListLocate_L(L,x); //對循環鏈表執行查找操作
if(n==2)
ListInsert_L(L,i,e); //對循環鏈表執行插入操作
if(n==3)
ListDelete_L(L,i,e); //對循環鏈表執行刪除操作
if(n==4)
return 0;} ////不對單鏈表執行任何操作
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -