单向链表模版代码:
功能:
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;
}