本題要求實現兩個函數,一個將輸入的學生成績組織成單向鏈表;另一個將成績低於某分數線的學生結點從鏈表中刪除。
函數接口定義:
struct stud_node *createlist(); struct stud_node *deletelist( struct stud_node *head, int min_score );
函數createlist
利用scanf
從輸入中獲取學生的信息,將其組織成單向鏈表,並返回鏈表頭指針。鏈表節點結構定義如下:
struct stud_node { int num; /*學號*/
char name[20]; /*姓名*/
int score; /*成績*/
struct stud_node *next; /*指向下個結點的指針*/ };
輸入為若干個學生的信息(學號、姓名、成績),當輸入學號為0時結束。
函數 deletelist
從以 head
為頭指針的鏈表中刪除成績低於 min_score
的學生,並返回結果鏈表的頭指針。
裁判測試程序樣例:
#include <stdio.h> #include <stdlib.h>
struct stud_node { int num; char name[20]; int score; struct stud_node *next; }; struct stud_node *createlist(); struct stud_node *deletelist( struct stud_node *head, int min_score ); int main() { int min_score; struct stud_node *p, *head = NULL; head = createlist(); scanf("%d", &min_score); head = deletelist(head, min_score); 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
80
輸出樣例:
2 wang 80
4 zhao 85
思路:這道題目的思路很簡單,每輸入一組數據,將該組數據存到一個臨時結點,再將這個結點與鏈表進行正確連接;刪除時從頭歷遍鏈表,刪除score<min_score 的結點。
但是,這道題我卻做了一節課,原因就是 對於每次輸入的數據,我沒有將它存到一個新創建的臨時結點,自始至終都存到了同一片空間,導致鏈表鏈接有問題。
代碼:
struct stud_node *createlist(){ int tem=0; struct stud_node *firstnode=NULL,*endnode=NULL; struct stud_node *temnode=(struct stud_node *)malloc(sizeof(struct stud_node)); while(scanf("%d", &temnode->num)&&temnode->num){ scanf("%s %d", &temnode->name,&temnode->score); temnode->next=NULL; if(tem==0){ tem=1; firstnode=endnode=temnode; } else{ endnode->next=temnode; endnode=endnode->next; } temnode=(struct stud_node *)malloc(sizeof(struct stud_node));//問題關鍵,之前少寫了這句話 } return firstnode; } struct stud_node *deletelist( struct stud_node *head, int min_score ){ while(head&&head->score<min_score) head=head->next; if(head==NULL) return NULL; struct stud_node *temnode=head->next; struct stud_node *prenode=head; while(temnode!=NULL){ if(temnode->score<min_score) prenode->next=temnode->next; else prenode=prenode->next; temnode=temnode->next; } return head; }