本題要求實現一個將輸入的學生成績組織成單向鏈表的簡單函數。
函數接口定義:
void input();
該函數利用scanf從輸入中獲取學生的信息,並將其組織成單向鏈表。鏈表節點結構定義如下:
struct stud_node {
int num; /*學號*/
char name[20]; /*姓名*/
int score; /*成績*/
struct stud_node *next; /*指向下個結點的指針*/
};
單向鏈表的頭尾指針保存在全局變量head和tail中。
輸入為若干個學生的信息(學號、姓名、成績),當輸入學號為0時結束。
裁判測試程序樣例:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct stud_node {
int num;
char name[20];
int score;
struct stud_node *next;
};
struct stud_node *head, *tail;
void input();
int main()
{
struct stud_node *p;
head = tail = NULL;
input();
for ( p = head; p != NULL; p = p->next )
printf("%d %s %d\n", p->num, p->name, p->score);
return 0;
}
/* 你的代碼將被嵌在這里 */
輸入樣例:
1 zhang 78 2 wang 80 3 li 75 4 zhao 85 0
輸出樣例:
1 zhang 78 2 wang 80 3 li 75 4 zhao 85
void input()
{
struct stud_node *q;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d", &q->num);
while(q->num != 0)
{
scanf("%s %d", q->name, &q->score);
if(head == NULL)
{
head = q;
head->next = NULL;
}
if(tail != NULL)//tail為開辟節點
{
tail->next = q;
}
tail = q;
tail->next = NULL;
q=(struct stud_node *)malloc(sizeof(struct stud_node));
scanf("%d", &q->num);
}
}
