單鏈表實現的學生管理系統
阿新 • • 發佈:2019-02-10
這個學生管理系統是通過單鏈表實現的,這個管理系統是為了讓我們更好得對連結串列進行操作。
如果有什麼不懂的,或者不對的地方可以在評論裡指出來哦,歡迎大家瀏覽。#include <stdio.h> #include <stdlib.h> #include <string.h> #include <malloc.h> struct Node { char name[10]; int num; int age; struct Node* next; }; //建立一個學生連結串列 struct Node* createlist() { struct Node* list = (struct Node*)malloc(sizeof(struct Node));//給list分配一個記憶體空間 list->next = NULL; return list; } //建立一個學生的結點 struct Node* createnode(char *newname, int newnum, int newage) { struct Node* node = (struct Node*)malloc(sizeof(struct Node)); //給結點分配一個記憶體空間 strcpy(node->name, newname); //把資訊放到結點中 node->age = newage; node->num = newnum; node->next = NULL; return node; } //在尾部插入一個學生的資訊 void insertback(struct Node* list, char *newname, int newnum, int newage) { struct Node* newnode = createnode(newname, newnum, newage); //找到尾結點 struct Node* temp = list;//移動的結點用來找到尾結點 while (temp->next != NULL) //一直移動到最後一個結點 { temp = temp->next; } newnode->next = NULL; temp->next = newnode; } //刪除學生資訊 //刪除資訊的時候我們需要定義兩個移動結點,用來找到需要刪除的結點和它前面一個結點 void deleteinfo(struct Node* list, int num) { struct Node* temp = list; //用來找到要刪除的前面一個結點 struct Node* p = list->next;//指向需要刪除的結點 while (p->num != num) { temp = temp->next; p = p->next; } temp->next = p->next; free(p); } //查詢學生的資訊 //和刪除學生差不多 void searchinfo(struct Node* list, char *name) { struct Node* temp = list->next; while (strcmp(temp->name, name) != 0) { if (temp->next == NULL) { printf("沒有此學生的資訊\n"); return; } temp = temp->next; } printf("姓名:%s\n編號:%d\n年齡 :%d\n\n", temp->name, temp->num, temp->age); } void print(struct Node* list)//列印所有的資訊 { struct Node* temp = list->next; if (temp == NULL) { printf("沒有學生資訊\n"); } while (temp) { printf("姓名:%s\n編號:%d\n年齡 :%d\n\n", temp->name, temp->num, temp->age); temp = temp->next; } } //struct Node* student = createlist(); void menu()//選單介面 { printf("****************************************\n"); printf("* 1、插入學生資訊 *\n"); printf("* 2、查詢學生資訊 *\n"); printf("* 3、列印所有資訊 *\n"); printf("* 4、刪除學生資訊 *\n"); printf("* 5、退出管理系統 *\n"); printf("****************************************\n"); } int choice()//選擇需要的操作 { int choice; printf("請選擇您要執行的操作\n"); scanf("%d", &choice); while (choice < 1 || choice > 5) { printf("您的輸入有誤,請重新輸入\n"); scanf("%d", &choice); } return choice; } void work(struct Node* student) { menu(); int a = choice(); switch (a) { case 1: { char name[10] = "0"; int num = 0; int age = 0; printf("輸入資訊姓名,編號,年齡\n"); scanf("%s",name); scanf("%d", &num); scanf("%d", &age); insertback(student, name, num, age); }break; case 2: { char searchname[10] = "0"; printf("請輸入你要查詢的學生的名字\n"); scanf("%s", searchname); searchinfo(student, searchname); }break; case 3: { print(student); }break; case 4: { int deletenum = 0; printf("請輸入你要刪除的學生的編號\n"); scanf("%d", &deletenum); deleteinfo(student, deletenum); }break; case 5: { exit(0); }break; default: printf("輸入錯誤\n"); break; } } int main() { struct Node* student = createlist(); while (1) { work(student); } system("pause"); return 0; }