首先我來介紹一下要實現的的單鏈表基本基本操作有哪些:建立節點,頭尾的插入和刪除,某個位置的插入和刪除,查詢某個資料是否存在於單鏈表中。
我們將從以下四方面對上述操作進行實現。
1、單鏈表的結構體
2、以下是我們要實現的函式介面:typedef
struct listnode
listnode;
3、函式實現(**中包括了對每個函式各種情況的分析)listnode* buy_node(datatype x); //建立乙個節點
void printlist(listnode* phead);//列印鍊錶
void pushback(listnode** pphead, datatype x);//尾插
void popback(listnode** pphead);//頭插
void popback(listnode** pphead);//尾刪
void pushfront(listnode** ppnode, datatype x);//頭刪
listnode* find(listnode* phead, datatype x);//查詢乙個資料x
//在pos前面插入乙個資料
void insert(listnode** pphead, listnode* pos, datatype x);
void erase(listnode** pphead, listnode* pos);//刪除pos位置的資料
4、函式測試**(含結果)//傳二級指標,pphead是乙個二級指標,是第乙個指向第乙個節點的指標的位址
listnode* buy_node(datatype x)
//列印鍊錶只需要遍歷一遍鍊錶
void printlist(listnode* phead)
printf("\n");
}void pushback(listnode** pphead, datatype x)
//2.鍊錶不為空,找尾節點,再插入乙個新節點
else
tail->next = buy_node(x);
}}//尾刪:要找到尾節點和尾節點的前乙個節點,讓其指向空,避免野指標
//1.判斷鍊錶是否為空,不能直接刪除
//2.鍊錶有乙個節點,刪除,置空
//3.找尾節點,刪除尾節點
void popback(listnode** pphead)
else
prev->next = null;
free(cur);
}}//頭插
//1.如果鍊錶為空,buynode乙個節點
//2.如果不為空,直接在頭結點前面鏈入乙個節點,但是要注意的是現在頭結點已經變成了新加的節點
void pushfront(listnode** ppnode, datatype x)
}//頭刪
//1.判斷單鏈表是否為空,若為空則直接返回
//2.單鏈表只有乙個節點,先把free掉,把節點置空(因為那個節點是malloc出來的,所以要free掉,否則可能出現記憶體洩漏)
//3.正常情況:1)先找到頭結點的下乙個節點,儲存乙份,然後刪除頭結點,頭結點指向第二個節點
void popfront(listnode** pphead)
else
}//在鍊錶中查詢資料(x),初步想法是遍歷一遍鍊錶,對比查詢,找到則返回節點指標,沒找到返回null
listnode* find(listnode* phead, datatype x)
else
cur = cur->next;
}printf("找不到\n");
return null;
}// 在pos的前面插入乙個節點x
void insert(listnode** pphead, listnode* pos, datatype x)
listnode*temp = buy_node(x);
temp->next=pos;
prev->next=temp;
}}//刪除某一位置的節點:找到那個位置
//1.空鍊錶不能刪除
//2.
void erase(listnode** pphead, listnode* pos)
prev->next = next;
free(pos);
}}
ps:以上測試**的標頭檔案在**中沒有寫出,如有需要,請讀者自己補充。void test()
int main()
單鏈表的基本操作(C語言實現)
單鏈表的初始化,建立,插入,查詢,刪除。include include typedef int elemtype 定義結點型別 typedef struct node node,linkedlist 單鏈表的初始化 linkedlist linkedlistinit 單鏈表的建立1,頭插法建立單鏈表...
C語言實現單鏈表的基本操作
listnode.h ifndef listnode h define listnode h include stdio.h include assert.h include stdlib.h typedef int datatype typedef unsigned int size t type...
單鏈表 的基本操作 c語言實現
鍊錶的基本操作 c語言實現 執行環境 dev c 5.11 以下為原始碼,如有不正確的地方歡迎指正!include include define false 0 define true 1 typedef int datatype typedef struct nodelinklist linkli...