本題要求實現一個將輸入的學生成績組織成單向鏈表的簡單函數。
函數接口定義:
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
思路:創建個臨時節點指針 *temnode,其指向的空間用來存儲每次輸入的數據。對於第一組數據,head 和 tail 同時指向其存儲空間,即 head = tail = temnode;對之後的數據 head 不再變化, tail 的下級指針指向數據存儲空間 ,即 tail -> next = temnode,然後 tail 指針移位, tail = tail —>next。
注意:臨時節點指針的創建有固定套路:
struct stud_node temnode = (struct stud_node)malloc(sizeof(struct stud_node));
代碼:
void input() {
int tem = 0;
int thenum;
while (scanf("%d",&thenum)&&thenum){
struct stud_node *temnode = (struct stud_node*)malloc(sizeof(struct stud_node));
temnode->num = thenum;
scanf("%s %d", temnode->name, &temnode->score);
if (tem == 0) {
tem = 1;
tail = head = temnode;
}
else {
tail->next = temnode;
tail = tail->next;
}
}
}
之前的錯誤思路:head 和 tail 同時指向一片新的存儲空間,即
tail = head = (struct stud_node*)malloc(sizeof(struct stud_node));
每次輸入的數據,存儲到 tail 指向的空間,
再令 tail 的下級指針指向一片新的存儲空間,tail 指針移位, tail = tail->next;
所有數據輸入完畢,此時 tail 指向的空間沒有存儲數據,所以 delete tail,tail =NULL;但問題是 delete 並非真正刪除 tail ,tail 會隨機指向一個空間,直到程序完全結束,
所以沒有數據的 tail !=NULL,輸出時,會多輸出一行 0 0。
代碼:
void input() {
tail = head = new stud_node();
while (scanf("%d", &tail->num) && tail->num) {
scanf("%s %d", tail->name, &tail->score);
tail->next = new stud_node();
tail = tail->next;
}
delete tail;
tail = NULL;
}
(研究了一下午,終於整明白了!o( ̄▽ ̄)ブ)