#include
//主函数
#define SIZE sizeof(struct stu_node)
struct stu_node
{
int num;
char name[20];
int score;
struct stu_node *next;
};
int n; //n表示表中节点的个数
struct stu_node *create_stu(); //按输入顺序建立单向链表
void print_stu(struct stu_node *head); //遍历
struct stu_node *insert_stu(struct stu_node *head,struct stu_node *s);//插入
struct stu_node *delete_stu(struct stu_node *head,int num);//删除
main()
{
struct stu_node *head,*p;
int choice,num;
do
{
printf("请选择菜单(0-4):\n");
printf("\t1.建立链表\t2.插入\t3.删除\t4.遍历\t0.退出\n");
scanf("%d",&choice);
switch(choice)
{
case 1:head=create_stu();break;
case 2:printf("请输入待插入的学生信息:\n");
// p=(struct stu_node *)malloc(n*SIZE);
p=(struct stu_node *)malloc(SIZE);
scanf("%d%s%d",&p->num,p->name,&p->score);
head=insert_stu(head,p);
free(p);
break;
case 3:printf("请输入待删除的学生学号:");
scanf("%d",&num);
head=delete_stu(head,num);
break;
case 4:print_stu(head);
case 0:break;
}
}while(choice!=0);
}
//建立链表
struct stu_node * create_stu()
{
struct stu_node *head,*last,*p;
head=last=NULL;
n=0;
printf("请输入学号、姓名、成绩(学号为0时停止输入):\n");
do
{
p=(struct stu_node *)malloc(SIZE);
scanf("%d%s%d",&p->num,p->name,&p->score);
p->next=NULL;
if(p->num==0)break;
else if(head==NULL)head=p;
else last->next=p;
last=p;
n++;
}while(1);
free(p);
return head;
}
//遍历链表
void print_stu(struct stu_node *head)
{
struct stu_node *p;
p=head;
if(head==NULL)
{
printf("空表,无记录\n");
return;
}
printf("\n学号 姓名 成绩\n");
do
{
printf("%4d %s %d\n",p->num,p->name,p->score);
p=p->next;
}while(p!=NULL);
}
// 插入有问题
struct stu_node *insert_stu(struct stu_node *head,struct stu_node *s)
{
struct stu_node *p,*q;
p=head;
if(head==NULL)
{
head=s;
s->next=NULL;
}
else
{
while((s->num>p->num)&&(p->next!=NULL))
{
q=p;
p=p->next;
}
if(s->num<=p->num)
{
if(p==head)head=s;
else q->next=s;
s->next=p;
}
else
{
p->next=s;
s->next=NULL;
}
}
n++;
return head;
}
//删除
struct stu_node *delete_stu(struct stu_node *head,int num)
{
struct stu_node *p,*q;
if(head==NULL)
{
printf("链表为空!\n");
return NULL;
}
p=head;
while(num!=p->num&&p->next!=NULL)
{
q=p;
p=p->next;
}
if(num==p->num)
{
if(p==head)head=p->next;
else q->next=p->next;
printf("已删除:%d\n",num);
free(p);
n--;
}
else printf("%d 表中无此节点!\n",num);
return head;
}