任务:看程序,充分理解知识
链表复习
今天学习建立一条有序链表,定义3个函数来实现建立链表,输出链表,释放链表,链表成绩升序排列
#include<iostream.h>
#define NULL 0
struct Node{
int id,age;
char name[10];
float c;
Node *next;
};
Node *Create(int n)
{
Node *p,*p1,*p2,*h=NULL;
int i=0;
if(n<1) return NULL;
while(i<n){
p=new Node;
cin>>p->id>>p->name>>p->age>>p->c;
p->next=NULL;
if(h==NULL) h=p; //如果是空表,将新产生的结点P作为首结点
else{ //否则将其它结点插入链表;
p1=p2=h;
while(p2&&p->c>=p2->c){ //查找插入位置
p1=p2;
p2=p1->next;
}
if(p2==h){ //将新建立的结点插入链首;
p->next=p2;
h=p;
}
else{ //新建立的结点插入链首;
p->next=p2;
p1->next=p;
}
}
i++;
}
return h;
}
void print(Node *h) //输出链表
{
Node *p;
p=h;
while(p!=0){
cout<<p->id<<'\t'<<p->name<<'\t'<<p->age<<'\t'<<p->c<<endl;
p=p->next;
}
cout<<endl;
}
void deletechain(Node *h) //释放链表
{
Node *p;
while(h){
p=h;
h=h->next;
delete p;
}
}
void main()
{
int n;
cout<<"请输入班级人数"<<endl<<"班级人数为:";
cin>>n;
cout<<endl;
cout<<"
请输入班级学生信息!"<<endl;
cout<<"学号 姓名 年龄 成绩"<<endl;
Node *h;h=Create(n);
cout<<"建立的链表为:"<<endl;
cout<<endl<<"学号 姓名 年龄 成绩"<<endl;
print(h);
deletechain(h);
}