学生信息管理:添加、删除、查询与修改等
#include<iostream>
using namespace std;
struct Student{
int id;
char name[10];
Student *next;
};
Student *createNode(){
Student *stu=(Student *)malloc(sizeof(Student));
cout<<"请输入学生号:";
cin>>stu->id;
cout<<"请输入学生名:";
cin>>stu->name;
stu->next=NULL;
return stu;
}
void add(Student *head){
Student *node=createNode();
Student *p=head;
while(p->next)
p=p->next;//先找到最后一个节点
p->next=node;
node->next=NULL;
}
void add1(Student *head){
//在开头加。
Student *node=createNode();
node->next=head->next;
head->next=node;
}
void insert(Student *head){
Student *p=createNode();
Student *curr=head->next;
Student *pre=head;
while(curr){
if(curr->id>p->id){
break;
}
pre=curr;
curr=curr->next;
}
pre->next=p;
p->next=curr;
}
void remove(int i,Student *head){
Student *curr=head->next;
Student *pre=head;
bool flag=false;
if(!curr){
flag=true;
}
while(curr){
if(curr->id==i){
pre->next=curr->next;
free(curr);
flag=false;
break;//释放空间时存在问题!原来是忘记加break了
}
pre=curr;
curr=curr->next;
flag=true;
}
if(flag){
cout<<"无此学生!";
}
}
void show(Student *head){
Student *p=head;
cout<<"-----------------------------------"<<endl;
cout<<"学号\t"<<"姓名"<<endl;
while(p->next){
p=p->next;
cout<<p->id<<"\t"<<p->name<<endl;
}
cout<<"-----------------------------------"<<endl;
}
Student stu[]={
{201501,"张三",0},
{201502,"李四",0},
{201503,"王五",0},
{201504,"光头",0}
};
Student *find(Student *head,int id){
Student *result;
while(head){
if(head->id==id){
result=head;
return result;
}
head=head->next;
}
return NULL;
}
int main2(){
/*
stu[0].next=&stu[1];
stu[1].next=&stu[2];
stu[2].next=&stu[3];
stu[3].next=0;
Student *p=stu;
Student *p1=find(stu,201503);
if(p1){
cout<<"姓名:"<<p1->name<<"学号:"<<p1->id<<endl;
}
while(p){
cout<<"姓名:"<<p->name<<"学号:"<<p->id<<endl;
p=p->next;
}
*/
Student m_head={0};
do{
insert(&m_head);
show(&m_head);
remove(1,&m_head);
}while(1);
system("pause");
return 0;
}