单链表实例之学生系统
生活随笔
收集整理的這篇文章主要介紹了
单链表实例之学生系统
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
單鏈表實例之學生系統
#include<stdio.h> #include<stdlib.h>#define NAME_LEN 20typedef struct node {int number;char *name;struct node *next; } node_t;node_t *g_head; int add_stu() {node_t *new, *tmp;tmp = g_head;char *name;new = (node_t *)malloc(sizeof(node_t));if (new == NULL) {printf("malloc new node fail.\n");return -1;}new->name = (char *)malloc(NAME_LEN);if (new->name == NULL) {printf("malloc new node name fail.\n");return -1;}printf("input student number:");scanf("%d", &new->number);printf("input student name:");scanf("%s", new->name);if (g_head == NULL) {g_head = new;} else {while(tmp->next != NULL) {tmp = tmp->next;}tmp->next = new;new->next = NULL;}printf("input student success.\n");return 0; }int input_stu() {int choose;printf("1.input student message.\n");printf("2.back.\n");while (1) {printf("please choose:");scanf("%d", &choose);switch (choose) {case 1:add_stu();break;case 2:return -1;break;default:printf("error.\n");}printf("1.input student message.\n");printf("2.back.\n");}return 0; }int output_stu() {char *name;int number;node_t *new, *tmp;tmp = g_head;if (g_head == NULL) {printf("Student system is null.\n");} else {while (tmp != NULL) {printf(" %d ", tmp->number);printf(" %s \n", tmp->name);tmp = tmp->next;} }return 0; }int destroy_list() {printf("start destroy list.\n");node_t *list, *tmp;list = g_head;while (list != NULL) {tmp = list;free(tmp->name);free(tmp);list = list->next;}printf("destroy list success.\n");return 0; }int main() {char c;int choose;printf("Student system.\n");printf("1.input student message.\n");printf("2.output student message.\n");printf("3.exit.\n");printf("please choose:");scanf("%d", &choose);while (1) {if (choose == 3) {break;}switch (choose) {case 1:input_stu();break;case 2:output_stu();break;default:printf("error.\n");}printf("1.input student message.\n");printf("2.output student message.\n");printf("3.exit.\n");printf("please choose:");scanf("%d", &choose);}destroy_list();return 0; }運行結果演示:
1、復制代碼到main.c文本中。
2、在linux系統下編譯成可執行文件main,gcc main.c -o main。
3、編譯目錄下執行./main運行。
總結
以上是生活随笔為你收集整理的单链表实例之学生系统的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 地下城与勇士大转移红眼首饰
- 下一篇: 长河落日剧情介绍