stack_list.c (1990B)
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 5 struct Student { 6 char name[50]; 7 float grade; 8 int id; 9 struct Student *next; 10 }; 11 12 struct Student *head; 13 14 static void 15 push(struct Student *s) 16 { 17 struct Student *p; 18 19 if ((p = malloc(sizeof(struct Student))) == NULL) { 20 fputs("malloc failed\n", stderr); 21 exit(EXIT_FAILURE); 22 } 23 24 *p = *s; 25 p->next = head; 26 head = p; 27 } 28 29 static void 30 pop(void) 31 { 32 struct Student *p; 33 34 if (head != NULL) { 35 p = head; 36 head = head->next; 37 free(p); 38 } 39 } 40 41 static void 42 print(void) 43 { 44 struct Student *p; 45 46 for (p = head; p != NULL; p = p->next) 47 printf("Name: %s | ID: %d | Grade: %.2f\n", p->name, p->id, p->grade); 48 } 49 50 int 51 main(int argc, char *argv[]) 52 { 53 struct Student stud; 54 int ch = -1; 55 56 head = NULL; 57 58 while (ch != 0) { 59 puts("1. Push"); 60 puts("2. Pop"); 61 puts("3. Print"); 62 puts("0. Exit"); 63 printf("\nYour choice: "); 64 scanf("%d", &ch); 65 getchar(); 66 67 switch (ch) { 68 case 1: 69 printf("Name: "); 70 fgets(stud.name, sizeof(stud.name), stdin); 71 stud.name[strlen(stud.name) - 1] = '\0'; 72 printf("ID: "); 73 scanf("%d", &stud.id); 74 getchar(); 75 printf("Grade: "); 76 scanf("%f", &stud.grade); 77 getchar(); 78 push(&stud); 79 break; 80 case 2: 81 pop(); 82 break; 83 case 3: 84 print(); 85 break; 86 } 87 } 88 89 return 0; 90 }