C語言——單鏈表的增刪改查
阿新 • • 發佈:2018-12-08
我們需要先定義一下連結串列的結構
#ifndef LIST_H #define LIST_H #define L 50 //引入標頭檔案 #include<stdio.h> #include<string.h> #include<stdbool.h> #include<stdlib.h> //定義連結串列資料域的資料結構體 typedef struct message { char name[20]; int age; } Item; //定義連結串列 typedef struct node { Item item; struct node * next; } Node, *List; List creat(void); bool add(List head); bool del(List head); bool change(List head); bool search(List head); void traverse(List head); #endif
在這個基礎上,我們實現以下相關的函式,我們先初始化一下連結串列。操作如下,先為連結串列建立一個頭節點,為該節點分配記憶體,但不存放資料
List creat(void)
{
List head = (List)malloc(sizeof(Node));
//將頭節點的下一個節點設定為NULL
head->next = NULL;
return head;
}
此時初始化完成,下面我們再實現一下增刪改查的功能
bool add(List head) { //輸入新結點的資料 Item people; printf("Please input your name:"); gets(people.name); printf("Please input your age:"); scanf("%d", &people.age); //清空緩衝區 getchar(); //使用頭插法插入資料 List p = (List)malloc(sizeof(Node)); p->item = people; p->next = head->next; head->next = p; return true; } bool del(List head) { char nameWillBeenDelete[L]; printf("Please input the student's name who will you delete:"); gets(nameWillBeenDelete); List prev = head; List p = prev->next; //查詢資料,如果查詢到,則在成功刪除後return true while (NULL != p) { if (!strcmp(p->item.name, nameWillBeenDelete)) { List t = p; prev->next = p->next; printf("%s has been delete!\n", t->item.name); free(t); return true; } prev = p; p = p->next; } //如果查詢完所有資料都沒有找到,則return false puts("Not found!"); return false; } //修改資料,與刪除類似 bool change(List head) { char nameWillBeenChange[L]; printf("Please input the student's name who will you change:"); gets(nameWillBeenChange); List p = head->next; while (NULL != p) { if (!strcmp(p->item.name, nameWillBeenChange)) { printf("Please input your new name:"); gets(p->item.name); printf("Please input your new age:"); scanf("%d", &p->item.age); getchar(); printf("New:name:%s age:%d\n", p->item.name, p->item.age); return true; } p = p->next; } puts("Not found!"); return false; } //查詢 bool search(List head) { char nameWillBeenSearch[L]; printf("Please input the student's name who will you search:"); gets(nameWillBeenSearch); List p = head->next; while (NULL != p) { if (!strcmp(p->item.name, nameWillBeenSearch)) { printf("message: name:%s age:%d\n", p->item.name, p->item.age); return true; } p = p->next; } printf("Not Found!\n"); return false; }
我們已經定義好了連結串列的結構,並且也封裝號了相關的功能,因此,我們只需要在main()函式中呼叫即可
#include"list.h" int main(void) { //建立一個連結串列 List head = creat(); int n; printf("Please input how number sutdents will you want:"); scanf("%d", &n); getchar(); for (int i = 0; i < n; i++) { add(head); } del(head); change(head); search(head); traverse(head); return 0; }
下面是執行結果
GitHub原始碼地址
需要的可以自行下載