//链表 #include<iostream> #include<algorithm> using namespace std; typedef struct LNode { int data; struct LNode *next; }LNode,*LinkList; int InitList_L(LinkList &L) { L=new LNode; L->next=NULL; return 1; } void Input_L(LinkList &L,int n) { int i; LNode *p,*r; cout<<"请输入"<<n<<"个数:\n"; r=L; for(i=0;i<n;i++) { p=new LNode; cin>>p->data; p->next=NULL; r->next=p; r=p; } } int LocateElem_L(LinkList &L,int e) { LNode *p;//p=new LNode; p=L->next; while(p&&p->data!=e) { p=p->next; } e=p->data; return e; } int ListInsert_L(LinkList &L,int i,int e) { LNode *p,*s; p=L; int j=0; while(p&&j<i-1) { p=p->next; j++; } if(!p||j>i-1) return 0; s=new LNode; s->data=e; s->next=p->next; p->next=s; return 1; } int ListDelete_L(LinkList &L,int i,int &e) //??? { LNode p; p = new LNode; LNode *q; p=L; int j=0; while(p->next && j<i-1) { p=p->next; j++; } if(!(p->next) || j>i-1) return 0; q=p->next; p->next=q->next; e=q->data; delete q; return 1; } void Output_L(LinkList L) { LNode *p; p=L->next; while(p!=NULL) { cout<<p->data<<" "; p=p->next; } cout<<endl; } int main() { LinkList L; int e,res,temp,num,i,a,k; cout<<"1. 建立链表"<<endl; cout<<"2. 输入数据"<<endl; cout<<"3. 查找"<<endl; cout<<"4. 插入"<<endl; cout<<"5. 删除"<<endl; cout<<"6. 输出数据"<<endl; cout<<"0. 退出"<<endl; int choose=-1; while(choose!=0) { cout<<"请选择:"<<endl; cin>>choose; switch(choose) { case 1: if(InitList_L(L)) //创建链表 cout<<"成功建立链表"<<endl; else cout<<"链表建立失败"<<endl; break; case 2: cout<<"请输入单链表的个数:"<<endl; cin>>num; Input_L(L,num); //输入数据 break; case 3: cout<<"请输入要查找的数:"<<endl; cin>>e; temp=LocateElem_L(L,e); if(temp) { cout<<e<<"是第"<<temp<<"个数."<<endl<<endl; } else { cout<<"查找失败!不存在这个数!!!"<<endl<<endl;//cout<<"查找失败!不存在这个数!!!\n\n"; 另一种写法 } break; case 4: cout<<"请分别输入插入位置和插入数据"<<endl; cin>>i>>a; if(ListInsert_L(L,i,a)) cout<<"插入成功"<<endl; else cout<<"插入失败"<<endl; break; case 5: cout<<"请输入要删除数的序号:"<<endl; cin>>k; if(ListDelete_L(L,k,res)) cout<<"删除成功."<<endl<<"被删除的数为:"<<res<<endl<<endl; else cout<<"删除失败."<<endl<<endl; break; case 6: cout<<"当前链表为:"<<endl; Output_L(L); cout<<endl; } } return 0; }
时间: 2024-10-26 09:23:19