【數據結構】(C語言):鏈表

鏈表:

  • 基本單位是節點。節點至少兩部分:數據,下一個數據的地址。
  • 頭指針head,始終指向鏈表的第一個節點。若沒有節點,則head=NULL。
  • 鏈表在內存中是非連續的。不能使用索引(下標)查找元素。只能從頭遍歷。
  • 鏈表有單鏈表、循環單鏈表、雙鏈表、循環雙鏈表。本文以單鏈表舉例。

添加節點:(注意指向順序,避免數據丟失)

  • 在鏈表頭部添加:先新節點指向第一個節點,再頭指針指向新節點。
  • 在鏈表尾部添加:最后一個節點指向新節點。
  • 在鏈表指定位置添加:找到指定位置,先新節點指向下一個節點,再上一個節點指向新節點。

?刪除節點:

  • 刪除鏈表頭部節點:頭指針指向第二個節點。
  • 刪除鏈表尾部節點:倒數第二個節點指向NULL。
  • 刪除鏈表指定位置節點:找到指定位置,上一個節點指向該節點的下一個節點。


?C語言代碼:

創建節點(結構體數據類型),并創建具體節點實例的函數:

// 節點(結構體數據類型)
typedef struct Node
{int data;                 // 數據為整數struct Node *next;        // 指針指向下一個節點
} LinkNode;                   // 別名LinkNode
// 創建具體節點實例的函數
LinkNode * createNode(int data)
{LinkNode *node = (LinkNode *)malloc(sizeof(LinkNode));   // 給節點分配內存空間if(node == NULL){perror("Memory allocation failed");exit(-1);}node->data = data;node->next = NULL;return node;
}

本文將頭指針和鏈表長度作為全局變量:

LinkNode *header = NULL;		// 頭指針,初始化指向NULL
int length = 0;				    // 統計鏈表元素個數

添加節點:

// 添加節點(鏈表頭部添加)
void addtop(int data)
{LinkNode *node = createNode(data);       // 調用createNode函數,創建具體節點node->next = header;                     // 先新節點指向頭指針指向的節點header = node;                           // 再頭指針指向新節點length++;                                // 每添加一個數據,length+1
}
// 添加節點(鏈表尾部添加)
void append(int data)
{if(length == 0)        // 若空鏈表,在鏈表頭部添加{addtop(data);return ;}LinkNode *node = createNode(data);LinkNode *cur = header;         // 從頭遍歷元素,找到最后while(cur->next != NULL){cur = cur->next;}cur->next = node;length++;
}
// 添加節點(在指定位置,位置從0開始)
void insert(int location, int data)
{if(length == 0)    // 若空鏈表,在鏈表頭部添加{addtop(data);return ;}if(length <= location)    // 若鏈表長度<=指定位置,在鏈表尾部添加{append(data);return ;}LinkNode *node = createNode(data);LinkNode *prev, *cur = header;      // 使用兩個指針,遍歷鏈表,找到指定位置while(location > 0){	prev = cur;cur = cur->next;location--;}node->next = cur;prev->next = node;length++;
}

刪除節點:

// 刪除節點(刪除鏈表頭部節點)
void pop(void)
{if(length == 0) return ;   // 空鏈表,直接退出程序header = header->next;length--;                  // 每刪除一個元素,length-1
}
// 刪除節點(刪除鏈表尾部節點)
void dellast(void)
{	if(length == 0) return ;       // 空鏈表,直接退出程序if(length == 1)                // 一個元素,頭指針直接指向NULL{header = NULL;return ;}LinkNode *prev, *cur = header;     // 使用兩個指針,遍歷鏈表,直到最后的位置while(cur->next != NULL){prev = cur;cur = cur->next;}prev->next = NULL;length--;
}
// 刪除節點(刪除鏈表指定位置的節點,位置從0開始)
void delat(int location)
{if(length == 0) return ;          // 空鏈表,直接退出程序if(length - 1 <= location)        // 鏈表長度-1<=指定位置,刪除鏈表尾部節點{dellast();return ;}LinkNode *prev, *cur = header;     // 使用兩個指針,遍歷鏈表,直到指定位置while(location > 0){prev = cur;cur = cur->next;location--;}prev->next = cur->next;length--;
}
// 刪除節點(刪除指定數據)
void del(int data)
{LinkNode *prev, *cur = header;      // 使用兩個指針,遍歷鏈表,比對數據內容while(cur != NULL){if(cur->data == data){if(header == cur)       // 若是第一個節點,頭指針直接跳過該節點指向下一個節點{header = cur->next;}else                    // 否則 該節點上一個節點,直接跳過該節點指向下一個節點{prev->next = cur->next;}length--;return ;}prev = cur;cur = cur->next;}return ;
}

遍歷節點:

void travel(void)
{if(length == 0) return ;       // 空鏈表,直接退出程序printf("linklist elements: ");LinkNode *cur = header;while(cur != NULL){printf("%d \t", cur->data);cur = cur->next;}printf("\n");
}


完整代碼:(linklist.c)

#include <stdio.h>
#include <stdlib.h>/* structure */
typedef struct Node			// node structure
{int data;struct Node *next;
} LinkNode;/* global variables */
LinkNode *header = NULL;		// header pointer
int length = 0;				    // the number of linklist elements/* function prototype */
void addtop(int data);			// add element to the top of the linklist
void append(int data);			// add element to the end of the linklist
void insert(int location, int data);	// add element to the specify location (start with 0)
void travel(void);			// show element one by one
void pop(void);				// delete element from the top of the linklist
void dellast(void);			// delete element from the end of the linklist
void delat(int location);		// delete element from the specify location (start with 0)
void del(int data);			// delete the specify data/* main function */
int main(void)
{addtop(5);printf("length is %d \n", length);		travel();append(9);printf("length is %d \n", length);		travel();insert(1,8);printf("length is %d \n", length);		travel();addtop(3);printf("length is %d \n", length);		travel();pop();	printf("length is %d \n", length);		travel();dellast();printf("length is %d \n", length);		travel();delat(1);printf("length is %d \n", length);		travel();del(7);printf("length is %d \n", length);		travel();del(5);printf("length is %d \n", length);		travel();
}/* subfunction */
LinkNode * createNode(int data)		// create a node
{LinkNode *node = (LinkNode *)malloc(sizeof(LinkNode));if(node == NULL){perror("Memory allocation failed");exit(-1);}node->data = data;node->next = NULL;return node;
}void addtop(int data)			// add element to the top of the linklist
{LinkNode *node = createNode(data);node->next = header;header = node;length++;
}void append(int data)			// add element to the end of the linklist
{if(length == 0){addtop(data);return ;}LinkNode *node = createNode(data);LinkNode *cur = header;while(cur->next != NULL){cur = cur->next;}cur->next = node;length++;
}	void insert(int location, int data)	// add element to the specify location (start with 0)
{if(length == 0){addtop(data);return ;}if(length <= location){append(data);return ;}LinkNode *node = createNode(data);LinkNode *prev, *cur = header;while(location > 0){	prev = cur;cur = cur->next;location--;}node->next = cur;prev->next = node;length++;
}void travel(void)			// show element one by one
{if(length == 0) return ;printf("linklist elements: ");LinkNode *cur = header;while(cur != NULL){printf("%d \t", cur->data);cur = cur->next;}printf("\n");
}void pop(void)				// delete element from the top of the linklist
{if(length == 0) return ;header = header->next;length--;
}void dellast(void)			// delete element from the end of the linklist
{	if(length == 0) return ;if(length == 1){header = NULL;return ;}LinkNode *prev, *cur = header;while(cur->next != NULL){prev = cur;cur = cur->next;}prev->next = NULL;length--;
}void delat(int location)		// delete element from the specify location (start with 0)
{if(length == 0) return ;if(length - 1 <= location){dellast();return ;}LinkNode *prev, *cur = header;while(location > 0){prev = cur;cur = cur->next;location--;}prev->next = cur->next;length--;
}void del(int data)			// delete the specify data
{LinkNode *prev, *cur = header;while(cur != NULL){if(cur->data == data){if(header == cur){header = cur->next;}else{prev->next = cur->next;}length--;return ;}prev = cur;cur = cur->next;}return ;
}

編譯鏈接: gcc -o linklist linklist.c

執行可執行文件: ./linklist

?

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/diannao/35186.shtml
繁體地址,請注明出處:http://hk.pswp.cn/diannao/35186.shtml
英文地址,請注明出處:http://en.pswp.cn/diannao/35186.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

解決:Xshell通過SSH協議連接Ubuntu服務器報“服務器發送了一個意外的數據包,received:3,expected:20”

下圖所示&#xff1a; 日志也基本看不出來問題在哪&#xff0c;只是說斷開了連接大概是驗證失敗。有幸在某論壇評論區找到了原因&#xff0c;是因為我的xshell版本太低了而服務器的ssh版本太高&#xff0c;高版本的ssh默認屏蔽了一部分不太安全的算法導致建立連接的時候驗證失敗…

C++ 14新特性個人總結

variable templates 變量模板。這個特性允許模板被用于定義變量&#xff0c;就像之前模板可以用于定義函數或類型一樣。變量模板為模板編程帶來了新的靈活性&#xff0c;特別是在定義泛化的常量和元編程時非常有用。 變量模板的基本語法 變量模板的聲明遵循以下基本語法&am…

解決Vue+Vite打包后Leaflet的marker圖標不顯示的問題

前言 用Leaflet寫關于WebGIS的開發&#xff0c;用Vite或者webpack打包&#xff0c;打包后會找不到圖標&#xff0c;如下所示。 直言的說&#xff0c;筆者去網上搜了搜&#xff0c;其實收到一個比較好是答案。網址如下。 &#xff08;完美解決~&#xff09;關于VueLeaflet添加…

eslint 與 prettier 的一些常見的配置項(很詳細)

目錄 1、eslint 常見配置項&#xff08;語法規范&#xff09; 2、 prettier 常見的配置項&#xff08;格式規范&#xff09; 代碼規范相關內容看小編的該文章&#xff0c;獲取對你有更好的幫助 vsCode代碼格式化&#xff08;理解eslint、vetur、prettier&#xff0c;實現格式…

IDEA啟動報錯:Abnormal build process termination...

一、問題描述 因為項目需要&#xff0c;同時打開了兩個idea&#xff0c;突然發現一個啟動的時候報錯&#xff0c;有點莫名其妙&#xff0c;剛還好好的&#xff0c;為啥就不能用了&#xff0c;一頓百度找方法&#xff0c;試了各種方法&#xff0c;像重新安裝jdk、重啟系統發現都…

TensorFlow開源項目

歡迎來到 Papicatch的博客 文章目錄 &#x1f349;TensorFlow介紹 &#x1f349;主要特點和功能 &#x1f348;多語言支持 &#x1f348;靈活的架構 &#x1f348;分布式訓練 &#x1f348;跨平臺部署 &#x1f348;強大的工具鏈 &#x1f348;豐富的社區和生態系統 &a…

c++基本數據類型和計算(一)習題講解

1.【單選題】以下說法正確的是? A. unsigned 類型的值 最大為0xFFFFFFFF B. float類型的值大約有15位精度 C.bool類型占用4個字節 解析&#xff1a; 選項A&#xff1a;unsigned 類型的值 最大為 4個字節&#xff0c;正確。選項B&#xff1a; 因為float類型的值是單精度的浮…

Vue3基礎使用

目錄 一、創建Vue3工程 (一)、cli (二)、vite 二、常用Composition API (一)、setup函數 (二)、ref函數 (三)、reactive函數 (四)、setup注意事項 (五)、計算屬性 (六)、watch (七)、watchEffect函數 (八)、生命周期 1、以配置項的形式使用生命周期鉤子 2、組合式…

kafka-簡單代碼實現生產者消費者

生產者代碼&#xff1a; package com.kafka.test;import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.kafka.common.seriali…

【機器學習-10】 | Scikit-Learn工具包進階指南:Scikit-Learn工具包之支持向量機模塊研究

&#x1f3a9; 歡迎來到技術探索的奇幻世界&#x1f468;?&#x1f4bb; &#x1f4dc; 個人主頁&#xff1a;一倫明悅-CSDN博客 ?&#x1f3fb; 作者簡介&#xff1a; C軟件開發、Python機器學習愛好者 &#x1f5e3;? 互動與支持&#xff1a;&#x1f4ac;評論 &…

高考填報志愿攻略,5個步驟選專業和院校

在高考完畢出成績的時候&#xff0c;很多人會陷入迷茫中&#xff0c;好像努力了這么多年&#xff0c;卻不知道怎么規劃好未來。怎么填報志愿合適&#xff1f;在填報志愿方面有幾個內容需要弄清楚&#xff0c;按部就班就能找到方向&#xff0c;一起來了解一下正確的步驟吧。 第…

入局AI手機 蘋果公布Apple Intelligence

日前&#xff0c;蘋果WWDC 2024如期召開。在這持續1個小時44分鐘的開發者大會上&#xff0c;蘋果在前一個小時里更新了iOS、iPadOS、MacOS等操作系統&#xff0c;而且還首次更新了visionOS。余下的時間全部留給了蘋果的“AI大禮包”——Apple Intelligence&#xff08;蘋果智能…

請說明Thread類中run和start的區別,從方法的區別,及運行結果的區別分別說明

方法本身的區別 start() 方法&#xff1a; run()方法是Thread類的一個普通方法&#xff0c;它包含了線程要執行的代碼。當你直接調用一個線程的run()方法&#xff08;如myThread.run()&#xff09;&#xff0c;你實際上是在當前線程&#xff08;通常是主線程&#xff09;中執行…

PointCloudLib-濾波模塊(Filtering)-使用參數化模型投影點

在本教程中,我們將學習如何將點投影到參數化模型上 (例如,平面、球體等)。參數模型通過一組 系數 – 在平面的情況下,通過其方程:ax + by + cz + d = 0。 代碼 #include <iostream> #include <pcl/point_cloud.h> // for PointCloud #include <pcl/point…

mysql是什么

mysql是什么 是DBMS軟件系統&#xff0c;并不是一個數據庫&#xff0c;管理數據庫 DBMS相當于用戶和數據庫之間的橋梁&#xff0c;有超過300種不同的dbms系統 mysql是關系型數據庫&#xff0c;關系型數據庫存儲模型很想excel&#xff0c;用行和列組織數據 sql是一門編程語言…

關于ip地址的網頁無法訪問navigator的gpu、媒體、藍牙等設備的解決方法

在使用threejs的WebGPURenderer渲染器時&#xff0c;發現localhost以及127.0.0.1才能訪問到navigator.gpu&#xff0c;直接使用ip會變成undefined,原因是為了用戶的隱私安全&#xff0c;只能在安全的上下文中使用&#xff0c;非安全的上下文就會是undefined&#xff0c;安全上下…

谷歌云(GCP)4門1453元最熱門證書限時免費考

谷歌云(GCP)最新活動&#xff0c;完成免費官方課程&#xff0c;送4門最熱門考試免費考試券1張(每張價值200刀/1453元)&#xff0c;這4門也包括最近大熱的AI/ML考試&#xff0c;非常值得學習和參加&#xff0c;活動7/17截止 谷歌云是全球最火的三大云計算廠商(前兩名AWS, Azure…

MySQL索引優化解決方案--索引失效(3)

索引失效情況 最佳左前綴法則&#xff1a;如果索引了多列&#xff0c;要遵循最左前綴法則&#xff0c;指的是查詢從索引的最左前列開始并且不跳過索引中的列。不在索引列上做任何計算、函數操作&#xff0c;會導致索引失效而轉向全表掃描存儲引擎不能使用索引中范圍條件右邊的…

【Linux】進程信號_1

文章目錄 八、進程信號1.信號 未完待續 八、進程信號 1.信號 信號和信號量之間沒有任何關系。信號是Linux系統提供的讓用戶/進程給其他進程發送異步信息的一種方式。 常見信號&#xff1a; 當信號產生時&#xff0c;可選的處理方式有三種&#xff1a;①忽略此信號。②執行該…