您的位置:首页 > 其它

一个链表程序,支持建立,插入,删除,输出;学生的学号和分数

2011-06-22 15:19 429 查看
#include <iostream.h>
#include <malloc.h>
#define NULL 0
#define LEN sizeof(struct stu)
#define BY (struct stu *)malloc(LEN)
typedef struct stu STU;
struct stu
{
long int num;
float score;
struct stu *next;
};
int n;
struct stu *creat()//建立链表
{
struct stu *p2,*p1,*head;
n=0;
p1=p2=BY;
cin>>p1->num>>p1->score;
head=NULL;
for(;p1->num!=NULL;)
{
n+=1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=BY;
cin>>p1->num>>p1->score;
}
p2->next=NULL;
return head;
}
void print(struct stu *head)//查询链表
{
struct stu *p;
cout<<"putout the students' number and score:/n";
p=head;
for(;p!=NULL;)
{
cout<<"number:"<<p->num<<"/tscore:"<<p->score<<endl;
p=p->next;
}
}

STU  *insert(STU *head,STU *std)//插入链表
{
STU *p0,*p1,*p2;

p1=head;
p0=std;
if(head==NULL)
{
head=p0;
p0->next=NULL;

}
else
{
while((p0->num>p1->num)&&(p1->next!=NULL))
{
p2=p1;
p1=p1->next;
}
if(p0->num<=p1->num)
{
if(head==p1)head=p0;
else p2->next=p0;
p0->next=p1;
}
else
{
p1->next=p0;
p0->next=NULL;
}
}
n+=1;
return head;
}

STU *dele(STU *head,long int num)//删除链表
{
STU *p1,*p2;
if(head==NULL)
{cout<<"empty list!/n";goto end;}
p1=head;
while(p1->num!=num&&p1->next!=NULL)
{p2=p1;p1=p1->next;}
if(p1->num==num)
{if(p1==head)head=p1->next;
else p2->next=p1->next;
n=n-1;
free(p1);
}
else cout<<"the node not been found!/n";
end:
return head;
}

int main(int argc, char* argv[])
{
struct stu *cl,*stud;
long int num;
int i;

cout<<"*************************************************/n"
<<endl
<<"selet the item                    *****/n"
<<"1:set the students' resoure       *****/n"
<<"2:query the students' resoure     *****/n"
<<"3:insert the students' resoure    *****/n"
<<"4:delete the students' resoure    *****/n"
<<"0:ESC the program!                *****/n"
<<endl
<<"************************************************/n";
do
{
cout<<"select the number to next/n";
cin>>i;
switch(i)
{
case 1:
{
cout<<"Please input the students' number and score:"<<endl
<<"number/tscore"<<endl;
cl=creat();
}break;
case 2:
{
cout<<"number/tscore"<<endl;
print(cl);
}break;
case 4:
{
cout<<"input the delete number:/n";
cin>>num;
cl=dele(cl,num);

}break;
case 3:
{
cout<<"input the insert number and score:/n";
stud=BY;
cin>>stud->num>>stud->score;
cl=insert(cl,stud);

}break;
case 0: break;
default:cout<<"input err/n";break;
}
}while(i!=0);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐