如下是本人完成的一個C語言創建鏈表並進行增刪查改操做的程序,爲方便學習,本人將整個程序分爲頭文件和主函數兩部分:java
(1)初始化函數git
#include <stdio.h> #include <stdlib.h> typedef struct { int *head; int length; int capacity; } Toslist; //Toslist類型 //初始化順序表 Toslist initSeqlist() { Toslist list; list.length = 0; list.capacity = 5; list.head = (int *)malloc(10 * sizeof(int)); if (!list.head) { printf("初始化失敗!\n"); exit(0); } return list; }
(2)打印函數github
//打印順序表 void displayList(Toslist list) { for (int i = 0; i < list.length; i++) { printf("%d ", list.head[i]); } printf("\n"); }
(3)插入函數函數
//插入元素 Toslist add(Toslist list, int elem, int pos) { if (list.length == list.capacity) { int *temp = (int *)realloc(list.head, (list.capacity + 1) * sizeof(int));//判斷空間是否足夠,不夠就另建鏈表 //不直接用head而引入temp的做用:防止空間分配失敗致使head失去原來的鏈表 if (!temp) { list.head = temp; list.capacity += 1; } } //插入位置及之後的元素後移 for (int i = list.length - 1; i >= pos; i--) { list.head[i + 1] = list.head[i]; } list.head[pos] = elem; list.length ++; return list; if (pos > list.length || pos < 0) printf("插入位置錯誤!\n"); return list; }
(4)刪除函數學習
//刪除元素 Toslist delete(Toslist list, int pos) { for (int i = pos; i < list.length - 1; i++) { list.head[i] = list.head[i + 1]; } list.length--; return list; if (pos < 0 || pos > list.length) { printf("刪除位置有誤!\n"); return list; } }
(5)查找函數.net
//查 int search(Toslist list, int elem) { //elem是查找的元素 //順序查找 for (int i = 0; i < list.length; i++) { if (elem == list.head[i]) { return i; } } return 0; }
(6)替換函數調試
//改 Toslist modify(Toslist list, int elem, int val) { //val是要替換它的元素 int pos = search(list, elem); //獲取要替換元素的位置 list.head[pos] = val; return list; }
int main() { Toslist list = initSeqlist(); int Addpos = -1, Addnum, Delpos, Serachnum,Modifynum; printf("請輸入5個整數元素\n"); for (int i = 0; i < 5; i++) { scanf("%d", &list.head[i]); list.length++; } printf("順序表中的元素有:\n"); displayList(list); //插入元素 printf("要在哪一個元素後插入元素?\n"); while (Addpos < 0 || Addpos > list.length) { scanf("%d", &Addpos); if (Addpos < 0 || Addpos > list.length) printf("請輸入正確的位置!\n"); }; printf("請輸入須要插入的元素:\n"); scanf("%d", &Addnum); printf("在順序表的第%d個元素後插入元素%d獲得\n", Addpos, Addnum); list = add(list, Addnum, Addpos); displayList(list); //刪除元素 printf("要刪除順序表下標順序中哪一個元素?\n"); scanf("%d", &Delpos); printf("刪除後獲得:\n"); list = delete(list, Delpos); displayList(list); //查找 printf("請輸入須要查找的元素\n"); scanf("%d", &Serachnum); int pos = search(list, Serachnum); if(pos) printf("元素%d的位置爲第%d個\n", Serachnum, pos+1); if(!pos){ printf("表中無該元素\n"); } //修改 printf("請輸入須要修改的元素:\n");scanf("%d",&Serachnum); printf("請輸入要替換的數:\n");scanf("%d",&Modifynum); printf("將%d修改成%d獲得:\n", Serachnum, Modifynum); list = modify(list, Serachnum, Modifynum); displayList(list); free(list.head); list.head = NULL; return 0; }
以上程序本人已調試完畢,若程序有繁雜之處,歡迎批評指正!code
若是有幫助,但願關注交流,謝謝🙏GershonHold的博客blog
個人GitHub地址:GershonHold的Githubci