單向鏈表模版代碼:
功能:
1、建立鏈表(2種)
2、按成績高低插入某學生成績
3、刪除某個作弊學生的成績
4、展示所有學生的成績
#include <iostream>
using namespace std;
typedef struct student {
int id;
float score;
struct student *next;
}stu, *stull;
void createtail(stull &head,int n){//尾插法
stull tail;
head = (struct student *)malloc(sizeof(stu));
head -> next = NULL;
tail = head;
for(int i=0; i<n; i++){
stull p;
p = (struct student *)malloc(sizeof(stu));
cout<<"輸入學生ID:"<<endl;
cin>> p->id;
cout<<"輸入學生成績:"<<endl;
cin>> p-> score;
if(head -> next == NULL){
head -> next = p;
p -> next = NULL;
tail = p;
}
else{
tail -> next = p;
p -> next = NULL;
tail = p; //注意tail的指向問題
}
}
}
/*當頭指針爲空時將頭指針指向p,p指向NULL,尾指針指向p
當頭指針不爲空時,尾指針指向p,p指向NULL,tail指向p。 */
void createhead(stull &head,int n){//頭插法
stull p;
head = (struct student *)malloc(sizeof(stu));
head -> next = NULL;
for(int i = 0; i<n; i++){
p=(struct student *)malloc(sizeof(stu));
cout<<"輸入學生ID:"<<endl;
cin>> p -> id;
cout<<"輸入學生成績:"<<endl;
cin>> p -> score;
if( head->next == NULL){
head -> next = p;
p -> next = NULL;
}
else{
p -> next = head -> next;
head -> next = p;
// p -> next=NULL;
}
}
}
/*當頭指針爲空,將頭指針指向p,p指向NULL
當頭指針不爲空時,將p指向首源節點,將頭指針指向p*/
void init(stull &head){//插入功能 不是初始化、、、
stull p;
p=(struct student *)malloc(sizeof(stu));
cout<<"插入學生ID:"<<endl;
cin >> p -> id;
cout<<"插入學生成績"<<endl;
cin >> p -> score;
stull t;
t=head;
for( ;t;t=t->next ){
if( t -> next->score > p->score && t->score < p->score){
p -> next = t->next;
t -> next = p;
break;
}
}
}
void delet(stull &head,int id){ //刪除id的節點
stull t;
t=head;
for(; t;t=t -> next){
if(t -> next -> id==id){
stull temp;
temp=t -> next;
t -> next = temp -> next;
free(temp);
break;
}
}
}
void display(stull &head){//展示功能
stull t;
t=head -> next;
while(t!=NULL){
cout<<"ID:"<< t->id <<endl;
cout << "score:" << t -> score << endl;
t = t -> next;
}
}
int main() {
stull head;
head=(struct student *)malloc(sizeof(stu));
int n;
cout<<"學生數目:"<<endl;
cin>>n;
createhead(head,n);
display(head);
int k;
cout<<"輸入作弊學生ID:"<<endl;
cin>>k;
delet(head,k);
display(head);
init(head);
display(head);
return 0;
}