建立一個連結串列,每個結點包括:學號、姓名、性別、年齡 輸入一個年齡,如果連結串列中的結點所包含的年齡等於此年齡,則將此結點刪去
阿新 • • 發佈:2020-09-08
建立一個連結串列,每個結點包括:學號、姓名、性別、年齡。輸入一個年齡,如果連結串列中的結點所包含的年齡等於此年齡,則將此結點刪去
#include <stdio.h> #include <stdio.h> typedef struct student { int num; char sex[10]; char name[100]; int age; struct student *next; } student; void printList(student *root) { printf("----\n"); while (root != NULL) { printf("num:%d, sex: %s, name: %s, age: %d\n", root->num, root->sex, root->name, root->age); root = root->next; } } int main() { student a[] = { { 1, "woman", "apple", 12 }, { 4, "woman", "banbana", 36 }, { 5, "man", "candy", 79 }, { 5, "man", "danny", 36 }, { 4, "man", "enjoy", 98 } }; for (int i = 0; i < 4; i++) { a[i].next = &a[i + 1]; } a[4].next = NULL; printList(&a[0]); int n; printf("請輸入要刪除的年齡:\n"); scanf("%d", &n); student *pre = a, *current = a->next, *head; head = a; while (current != NULL) { //如果頭結點需要刪除,則更新頭結點 if (head->age == n) { pre->next = NULL; pre = current; current = current->next; head = pre; } else { //刪除節點,重新連結 if (current->age == n) { pre->next = current->next; } pre = current; current = current->next; } } printList(head); return 0; }
執行截圖: