链表的操作

来源:互联网 发布:java websocket 心跳 编辑:程序博客网 时间:2024/05/01 23:54
·····

1.链表的建立{头插法,尾插法}

2.链表的输出

3.链表元素的查找

4.新元素的插入

5.元素的删除

#include <iostream>#include <iomanip>using namespace std;struct Student{int num;float score;Student *next;          //next指向Student结构体变量};int n;void main(){Student *Creat_front();     //按头插法创建链表,以-1 -1作为输入结束标志    Student *Creat_rear();      //按尾插法创建链表,以-1 -1作为输入结束标志    void Output(Student *head); //输出链表全部元素    Student *Locate(Student *head,int num); //给定学号,查找元素位置    void  LinkInsert(Student *head, Student *p); //向p指向的元素后插入一个新输入的元素    Student  *LinkDelete(Student *head, int num); //删除学号为num的元素    void Menu();  //简单的显示菜单int choose,num;Student *head,*p;Menu();       //显示菜单选项cin>>choose;while(choose!=0){switch(choose){case 1:   //头插法创建链表,与2不能同时使用head=Creat_front();break;case 2:   //尾插法创建链表head=Creat_rear();break;case 3:   //链表输出Output(head);break;case 4:   //查找元素cout<<"输入待查找NUM: ";cin>>num;p=Locate(head,num);if(p==NULL)cout<<"没有NUM为: "<<num<<"的同学信息"<<endl;elsecout<<"NUM为: "<<num<<"的同学成绩为: "<<p->score<<endl;break;case 5:   //插入元素LinkInsert(head,p);  //在查找到的元素后,插入一个新元素break;case 6:   //删除元素cout<<"输入要删除的NUM: ";cin>>num;head=LinkDelete(head,num);break;}Menu();cin>>choose;}}void Menu(){cout<<"-----------菜单----------"<<endl;cout<<"   1. 头插法创建链表"<<endl;cout<<"   2. 尾插法创建链表"<<endl;cout<<"   3. 链表输出"<<endl;cout<<"   4. 查找元素"<<endl;cout<<"   5. 插入元素"<<endl;cout<<"   6. 删除元素"<<endl;cout<<"   0. 退出"<<endl;cout<<"-------------------------"<<endl;cout<<"请选择: ";}Student *Creat_front(){Student *p1,*p2,*head1;n=0;p1=p2=new Student;cin>>p1->num>>p1->score;head1=NULL;while(p1->num!=-1&&p1->score!=-1){n=n+1;if(n==1)head1=p1;else p2->next=p1;p2=p1;p1=new Student;cin>>p1->num>>p1->score;}p2->next=NULL;return(head1);}Student *Creat_rear(){Student *p1,*p2,*head2;n=0;p1=p2=new Student;cin>>p1->num>>p1->score;head2=NULL;while(p1->num!=-1&&p1->score!=-1){n=n+1;if(n==1)head2=p1;else{cin>>p2->num>>p2->score;p1->next=p2;p1=p2;p2=new Student;}}p1->next=NULL;return(head2);}void Output(Student *head){Student *h;h=head;if(head!=NULL)do{cout<<"学号:"<<" "<<h->num<<"成绩:"<<" "<<h->score<<endl;h=h->next;}while(h!=NULL);}Student *Locate(Student *head,int num){Student *t;if(head==NULL)cout<<"此链表是空的"<<endl;elset=head;do{if(num==t->num)cout<<"该生学号为:"<<num<<"   "<<"该生成绩为:"<<t->score;elset=t->next;}while(t->next!=NULL);return t;}void  LinkInsert(Student *head, Student *p){Student *p0,*p1,*p2;p1=head;p0=p;if(head==NULL){head=p0;p0->next=NULL;}else{while((p0->num>p1->num)&&(p1->next!=NULL)){p2=p1;p1=p1->next;}if(p0->num<=p1->num){if(head==p1)head=p0;else p2->next=p0;p0->next=p1;}else{p1->next=p0;p0->next=NULL;}}n=n+1;}Student  *LinkDelete(Student *head, int num){Student *p1,*p2;if(head==NULL){cout<<"这是一个空表."<<endl;return(head);}p1=head;while(num!=p1->num&&p1->next!=NULL){p2=p1;p1=p1->next;}if(num==p1->num){if(p1==head)head=p1->next;elsep2->next=p1->next;cout<<"删除学号为:"<<num<<endl;n=n-1;}else cout<<"找不到节点"<<endl;return(head);}