網站首頁 編程語言 正文
前言
鏈表是一種動態的數據結構,因為在創建鏈表時,不需要知道鏈表的長度,只需要對指針進行操作。
1. 節點的創建
鏈表的節點包括兩部分,分別是:數據域和(指向下一個節點的)指針域。
struct Node { int data; struct Node* next; };
2. 鏈表的定義
struct Node* createList() { //創建一個指針來表示表頭 struct Node* headNode = (struct Node*)malloc(sizeof(struct Node)); headNode->next = NULL; return headNode; }
3. 創建節點
struct Node* createNode(int data) { //創建一個新的指針節點 struct Node* newNode = (struct Node*)malloc(sizeof(struct Node)); //結構體變量初始化 newNode->data = data; newNode->next = NULL; return newNode; }
4. 節點的插入
節點的插入分為三種:頭插法、尾插法、在鏈表中間插入節點。
?4.1 頭插法
頭插法,顧名思義就是在鏈表的第一個節點插入一個節點。
解決方法:讓新插入的節點的next指針指向鏈表的頭結點即可。
void insertNodeByHead(struct Node* headNode, int data) { struct Node* newNode = createNode(data); newNode->next = headNode->next; headNode->next = newNode; }
?4.2 尾插法
尾插法,顧名思義就是在鏈表的末尾增加一個節點。
解決思路:首先找到鏈表的最后一個節點;然后讓最后的節點的next指針指向要插入的這個節點,插入的節點的next指針指向NULL即可。
void insertNodeByTail(struct Node* headNode, int data) { struct Node* newNode = createNode(data); while (headNode->next != NULL) { headNode = headNode->next;//找到最后一個節點 } headNode->next = newNode; newNode->next = NULL; }
?4.3 插入中間節點
插入中間節點:即在數據為 i 的節點后面添加新的節點。
解決思路:首先判斷數據為?i 的節點posNode是否在鏈表中存在;然后從第一個節點開始查找節點posNode。找到后就讓插入的節點的next指針指向posNode的下一個節點,posNode的next指針指向新插入的節點即可。
void insertNodeByCenter(struct Node* headNode, int data, int i) { struct Node* posNode = headNode; /*struct Node* posNodeFront = headNode;*/ struct Node* newNode = createNode(data); if (posNode == NULL) { printf("無法查找此數據,鏈表為空\n"); } else { while (posNode->data != i) { posNode = posNode->next;//前面位置到達了后面節點的位置 /*posNode = posNodeFront->next;*///后面位置變成了原來位置的下一個 if (posNode == NULL) { printf("未找到此數據\n"); break; } } newNode->next = posNode->next; posNode->next = newNode; } }
?總結
原文鏈接:https://blog.csdn.net/qq_47635065/article/details/122388071
相關推薦
- 2022-11-21 詳解Go語言中的內存對齊_Golang
- 2022-05-25 Entity?Framework?Core對Web項目生成數據庫表_實用技巧
- 2022-07-14 Python內建類型list源碼學習_python
- 2022-06-24 SingleFlight模式的Go并發編程學習_Golang
- 2022-02-23 fatal error: mpi.h: No such file or directory // f
- 2023-11-16 當pytorch找不到 CUDA 時,如何修復錯誤:版本 libcublasLt.so.11 未在帶
- 2022-12-27 golang中日期操作之日期格式化及日期轉換_Golang
- 2022-04-25 C#利用NPOI操作Excel(單元格設置)_C#教程
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支