實(shí)際中經(jīng)常使用的一般為帶頭雙向循環(huán)鏈表。
單鏈表1
#include< stdio.h >
#include< stdlib.h >
typedef struct node
{
int data; //"數(shù)據(jù)域" 保存數(shù)據(jù)元素
struct node * next; //保存下一個(gè)數(shù)據(jù)元素的地址
}Node;
void printList(Node *head){
Node *p = head;
while(p != NULL){
printf("%dn",p- >data);
p = p - > next;
}
}
int main(){
Node * a = (Node *)malloc(sizeof(Node));
Node * b = (Node *)malloc(sizeof(Node));
Node * c = (Node *)malloc(sizeof(Node));
Node * d = (Node *)malloc(sizeof(Node));
Node * e = (Node *)malloc(sizeof(Node));
a- >data = 1;
a- >next = b;
b- >data = 2;
b- >next = c;
c- >data = 3;
c- >next = d;
d- >data = 4;
d- >next = e;
e- >data = 5;
e- >next = NULL;
printList(a);
}
結(jié)果:
這個(gè)鏈表比較簡單,實(shí)現(xiàn)也很原始,只有創(chuàng)建節(jié)點(diǎn)和遍歷鏈表,大家一看就懂!
單鏈表2
這個(gè)鏈表功能多一點(diǎn):
- 創(chuàng)建鏈表
- 創(chuàng)建節(jié)點(diǎn)
- 遍歷鏈表
- 插入元素
- 刪除元素
#include< stdio.h >
#include< stdlib.h >
typedef struct node
{
int data; //"數(shù)據(jù)域" 保存數(shù)據(jù)元素
struct node * next; //保存下一個(gè)數(shù)據(jù)元素的地址
}Node;
//創(chuàng)建鏈表,即創(chuàng)建表頭指針
Node* creatList()
{
Node * HeadNode = (Node *)malloc(sizeof(Node));
//初始化
HeadNode- >next = NULL;
return HeadNode;
}
//創(chuàng)建節(jié)點(diǎn)
Node* creatNode(int data)
{
Node* newNode = (Node *)malloc(sizeof(Node));
//初始化
newNode- >data = data;
newNode- >next = NULL;
return newNode;
}
//遍歷鏈表
void printList(Node *headNode){
Node *p = headNode - > next;
while(p != NULL){
printf("%dt",p- >data);
p = p - > next;
}
printf("n");
}
//插入節(jié)點(diǎn):頭插法
void insertNodebyHead(Node *headNode,int data){
//創(chuàng)建插入的節(jié)點(diǎn)
Node *newnode = creatNode(data);
newnode - > next = headNode - > next;
headNode - > next = newnode;
}
//刪除節(jié)點(diǎn)
void deleteNodebyAppoin(Node *headNode,int posData){
// posNode 想要?jiǎng)h除的節(jié)點(diǎn),從第一個(gè)節(jié)點(diǎn)開始遍歷
// posNodeFront 想要?jiǎng)h除節(jié)點(diǎn)的前一個(gè)節(jié)點(diǎn)
Node *posNode = headNode - > next;
Node *posNodeFront = headNode;
if(posNode == NULL)
printf("鏈表為空,無法刪除");
else{
while(posNode- >data != posData)
{
//兩個(gè)都往后移,跟著 posNodeFront 走
posNodeFront = posNode;
posNode = posNodeFront- >next;
if (posNode == NULL)
{
printf("沒有找到,無法刪除");
return;
}
}
//找到后開始刪除
posNodeFront- >next = posNode- >next;
free(posNode);
}
}
int main(){
Node* List = creatList();
insertNodebyHead(List,1);
insertNodebyHead(List,2);
insertNodebyHead(List,3);
printList(List);
deleteNodebyAppoin(List,2);
printList(List);
return 0;
}
結(jié)果:
大家從最簡單的單鏈表開始,學(xué)習(xí)鏈表的增刪改查,然后再學(xué)習(xí)雙鏈表,最后學(xué)習(xí)雙向循環(huán)鏈表。
-
數(shù)據(jù)結(jié)構(gòu)
+關(guān)注
關(guān)注
3文章
573瀏覽量
40664 -
單鏈表
+關(guān)注
關(guān)注
0文章
13瀏覽量
6997
發(fā)布評論請先 登錄
C語言單鏈表的應(yīng)用
數(shù)據(jù)結(jié)構(gòu):單鏈表的排序

單鏈表的缺陷是什么
C語言實(shí)現(xiàn)單鏈表舉例

C語言單鏈表的模擬學(xué)生成績管理系統(tǒng)
單鏈表學(xué)習(xí)的超詳細(xì)說明(二)
單鏈表學(xué)習(xí)的總結(jié)(一)
在STM32上創(chuàng)建鏈表并實(shí)現(xiàn)LCD滾動(dòng)顯示串口消息

雙向循環(huán)鏈表的創(chuàng)建
C語言_鏈表總結(jié)
鏈表的基礎(chǔ)知識(shí)

C語言的單鏈表應(yīng)用
單鏈表和雙鏈表的區(qū)別在哪里

雙向循環(huán)鏈表創(chuàng)建代碼

評論