一個學生的資訊是:姓名,學號,性別,年齡等資訊,用一個連結串列,把這些學生資訊連在一起, 給出一個age, 在些連結串列中刪除學生年齡等於age的學生資訊。
阿新 • • 發佈:2018-12-31
#include <stdio.h> #include <conio.h> #include <malloc.h> struct student { char name[12]; int number; char genda; int age; struct student *next; }; struct student *head; void creat(int nn) { int i; struct student *p,*q; if (NULL == nn || 0 >= nn) return; head = (struct student*)malloc(sizeof(struct student)); //head結構體單元 head->next = NULL; q = head; for (i = 0; i < nn; i++) //新建立了nn個結構體單元,故head單元實際不用 //連結串列的表頭,表尾可以用來儲存資料,也可以不儲存資料。沒有什麼強制規定。一般使用中,連結串列的表頭往往不儲存資料,表尾儲存資料的。
//表頭,之所以不儲存資料,是為了刪除資料時方便。 { p = (struct student*)malloc(sizeof(struct student)); q->next = p; printf("insert students' information:name number genda age \n"); scanf("%s %d %c %d",p->name,&(p->number),&(p->genda),&(p->age));//"%s %d %c %d\n"在scanf中\n不表示接受一個回車符,而是表示忽略所有的空白字//符,包括回車,空格,tab //,所以想要結束輸入,輸入任意一個非空白字元即可,但是該字元仍然會留在緩衝區中,所以一般不建議在 scanf中使用\n p->next = NULL; q = p; } printf("creat successfully\n"); } void delete_age(int age) { struct student *p,*q; p = head; while (p->next != NULL) { if (p->age != age) { q = p; p = p->next; } else { q->next = p->next; free(p); p = q->next; } } } void display() { student *s; printf("the students after delete_age:\n"); s = head->next; //沒有從head開始輸出,而是從head的下一個節點輸出 while (s != NULL) //s->next與s是同一型別,但是注意不要寫成s->next { printf("%s %d %c %d\n",s->name,s->number,s->genda,s->age); s = s->next; } } void main() { int n,age; struct student *p,*q; printf("insert the number of students:n="); scanf("%d",&n); creat(n); fflush(stdin); printf("insert the age:\n"); scanf("%d",&age); delete_age(age); display(); getch(); }