链表是一种常见的重要的数据结构,他是动态的进行存储分配的一种结构。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| #include <malloc.h> #include <stdio.h> #include <stdlib.h> #define NC sizeof(struct student) struct student //定义结构体数据类型 { int num; int score; struct student *next; }; int N;
struct student *creat(void); void print(); struct student *del();
int main() { struct student *stu, *p; int num;
stu = creat(); p = stu; print(p); printf("Please input the num to delete:"); scanf("%d", &num); print(del(p, num)); printf("\n\n"); system("pause"); return 0; }
struct student *creat(void) { struct student *p1, *p2, *head; p1 = p2 = (struct student *)malloc(NC); printf("please input num :"); scanf("%d", &p1->num); printf("please input score :"); scanf("%d", &p1->score); head = NULL; N = 0; while (p1->num) { N++; if (N == 1) { head = p1; } else { p2->next = p1; } p2 = p1; p1 = (struct student *)malloc(NC); printf("\nplease input num :"); scanf("%d", &p1->num); printf("please input score :"); scanf("%d", &p1->score); } p2->next = NULL; return head; }
void print(struct student *head) { struct student *p; printf("\nThere are %d records!\n", N); p = head; if (head) { do { printf("学号为%d的同学成绩是:%d\n", p->num, p->score); p = p->next; } while (p); } }
struct student *del(struct student *head, int num) { struct student *p1, *p2; if (head == NULL) { printf("\nThis is a NULL chart!"); goto END; } p1 = head; while (p1->num != num && p1->next != NULL) { p2 = p1; p1 = p1->next; } if (num == p1->num) { if (p1 == head) { head = p1->next; } else { p2->next = p1->next; } printf("\nDelete num:%d data success!", num); N--; } else { printf("\nnum:%d not been found!", num); } END: return head; }
|