学生成绩(链表)
#include<iostream>
#include<string>
using namespace std;
struct Student{string name;string score;Student *next;//定義了指向Candidate類型變量的指針
};
Student * Create(Student * head){Student *p=NULL;Student *node=NULL;int n;//cout<<"請輸入學生的總數(shù):";cin>>n;for(int i=1;i<=n;i++){node=new Student;cout<<"請輸入第"<<i<<"個同學的姓名:";cin>>node->name;cout<<"請輸入第"<<i<<"個同學的成績:";cin>>node->score;if(head==NULL)head=node;elsep->next=node;p=node;if(i==n){p->next=NULL;}}return head;
}
void Print(Student * head){Student *p=NULL;p=head;cout<<"鏈表已經(jīng)建立!"<<endl;cout<<"\n==========下面輸入剛才的數(shù)據(jù)=============\n"<<endl;int i=1;while(p!=NULL){cout<<"第"<<i<<"個同學==="<<p->name<<"==成績===="<<p->score<<endl;p=p->next;i++;}cout<<"\n"<<endl;
}
void Insert(Student * head,int k){Student *p=NULL;Student *node=NULL;p=head;if(k==1){node=new Student;cout<<"第1位同學的名字:";cin>>node->name;cout<<"第1位同學的成績:";cin>>node->score;node->next=head->next;head=node;}int i=1;while(p!=NULL){if(i+1==k){node=new Student;cout<<"第"<<k<<"位同學的名字:";cin>>node->name;cout<<"第"<<k<<"位同學的成績:";cin>>node->score;node->next=p->next;p->next=node;}p=p->next;i++;}
}void Destory(Student * head){Student *d;Student *p=NULL;p=head;while(p!=NULL){d=p;p=p->next;delete d;}
}
void Alter(Student * head,int k){int i=1;Student *p=head;while(p!=NULL){if(i==k){cout<<"第"<<k<<"位同學的名字:";cin>>p->name;cout<<"第"<<k<<"位同學的成績:";cin>>p->score;}p=p->next;i++;}
}
Student * Delete(Student * head,int k){int i=1;Student *p=head;Student *d=head;if(k==1){head=head->next;}else{while(p!=NULL){if(i+1==k){p->next=p->next->next;}p=p->next;i++;}}return head;
}
int main(){Student *head=NULL;//創(chuàng)建鏈表head=Create(head);//輸出鏈表Print(head);//插入數(shù)據(jù)int k;cout<<"請輸入你要插入的同學的序號:";cin>>k;Insert(head,k);//輸出鏈表Print(head);//修改鏈表cout<<"請輸入你要修改的同學的序號:";cin>>k;Alter(head,k);//輸出鏈表Print(head);//刪除其中的一個項cout<<"請輸入你要刪除的同學的序號:";cin>>k;head=Delete(head,k); //輸出鏈表Print(head);//銷毀鏈表Destory(head);return 0;
}
總結(jié)