输入若干个学生的信息(学号、姓名、成绩),当输入学号为0时结束,用单向链表组织这些学生信息后,再按顺序输出。
输入: 输出:
1 zhang 78 1 zhang 78
2 wang 80 2 wang 80
3 li 75 3 li 75
4 zhao 85 4 zhao 85
0
#include <stdio.h> #include <malloc.h> struct node { char name[10]; int num,score; struct node *next; }; struct node *create() { printf("请输入学生的信息,以输入学号为0结束\n"); printf("\t学号\t姓名\t分数\n"); struct node *Head,*p,*tail; int date; Head = (struct node *)malloc(sizeof(struct node)); Head->next = NULL; tail = Head; p = (struct node *)malloc(sizeof(struct node)); p->next = NULL; while(scanf("%d",&date) != EOF)
/*控制当学号为零就结束停止时,
不能直接通过控制结点,因为 那样会开辟一个结点,所以当输入为零 时,必须输入姓名分数才行,所以,要设置一个 变量,来控制分数的输入,当学号为零时,可 直接停止*/ { if(date == 0) break; p->num = date; scanf("%s %d",p->name,&p->score); tail->next = p; tail = p; p = (struct node *)malloc(sizeof(struct node)); p->next = NULL; } return Head; } void print(struct node *Head) { printf("\t\t学生信息输出\n"); printf("\t学号\t姓名\t分数\n"); struct node *p; p = Head->next; while(p != NULL) { printf("\t%d\t%s\t%d\n",p->num,p->name,p->score); p = p->next; } } int main() { struct node *head; head = create(); print(head); return 0; }