實驗1
輸入若干個學生的資訊(學號、姓名、成績),當輸入學號為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;}