天天看點

PTA 建立學生資訊連結清單建立學生資訊連結清單

建立學生資訊連結清單

題目連結 ,需要權限

本題要求實作一個将輸入的學生成績組織成單向連結清單的簡單函數。
函數接口定義:

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

輸出樣例:

1 zhang 78

2 wang 80

3 li 75

4 zhao 85

解題思路 :scanf 函數讀取完資料後用 getchar 讀取多餘的回車或空格符

void input()
{
	int n;
	scanf("%d", &n); getchar();
		if (n != 0)
		{
			struct stud_node *New = (struct stud_node *)malloc(sizeof(struct stud_node));
			head = New;
			head->num = n;
			//printf("1");
			scanf("%s", &head->name); getchar();
			scanf("%d",&head->score); getchar();
			head->next = NULL;
			struct stud_node *p = head;
			tail = p;
			scanf("%d", &n); getchar();
			while (n!=0)
			{
				//printf("1");
				struct stud_node *New = (struct stud_node *)malloc(sizeof(struct stud_node));
				p->next = New; tail = p->next;
				p = p->next;
				New->num = n;
				scanf("%s", &New->name); getchar();
				scanf("%d", &New->score); getchar();
				scanf("%d", &n); getchar();
			}
		}

}

           

繼續閱讀