C语言|C语言 单向链表的增删查改快速掌握
目录
- 前言
- 一、创建
- 二、单向链表的函数声明
- 三、函数实现
- 1.创建节点
- 2.尾插节点
- 3.头插
- 4.尾删
- 5.头删
- 6.查找节点
- 7.修改
- 总结
前言 链表是线性表的链式存储结构,它可以以O(1)的时间复杂度进行插入或者删除,同时由于是链式结构相比顺序表而言,不会存在空间浪费的情况。而链表又分为带头单向链表,不带头单向链表,带头循环链表,不带头循环链表,带头双向循环链表,不带头双向循环链表,带头双向链表,不带头双向链表,总共有八种,其中结构最简单的是不带头单向链表,也是实现起来最容易出错的。并且我们在网上进行链表的oj时,题目基本也是不带头的单向链表,而且也是互联网大厂面试中最容易考的。
一、创建
typedef int SLTDadaType; //存放的数据类型struct SListNode{ SLTDadaType _data; //存放的数据 struct SListNode* _next; //指向下一个节点的指针}; typedef struct SListNodeSListNode;
二、单向链表的函数声明
SListNode* BuyListNode(SLTDadaType x); //创建一个节点SListNode* SListPushBack(SListNode* head, SLTDadaType x); //尾插SListNode* SListPopBack(SListNode* head); //头插SListNode* SListPushFornt(SListNode* head, SLTDadaType x); //尾删SListNode* SListPopFornt(SListNode* head); //头删SListNode* SListFind(SListNode* head, SLTDadaType x); //查找一个节点void SListModify(SListNode* head, SLTDadaType x,SLTDadaType y); //x修改
三、函数实现
1.创建节点
SListNode* BuyListNode(SLTDadaType x){ SListNode* newnode = (SListNode*)malloc(sizeof(SListNode)); newnode->_data = https://www.it610.com/article/x; newnode->_next = NULL; return newnode; }
2.尾插节点
SListNode* SListPushBack(SListNode* head, SLTDadaType x){ SListNode* newnode = BuyListNode(x); //无论节点是否为空,都先进行创建一个节点 if (head == NULL)//头节点为空 {head = newnode; return head; } else //头节点不为空,直接遍历到链表结尾进行尾插 {SListNode* tail = head; while (tail->_next != NULL){tail = tail->_next; }tail->_next = newnode; return head; }}
3.头插
SListNode* SListPushFornt(SListNode* head, SLTDadaType x){ SListNode* newnode = BuyListNode(x); newnode->_next = head; head = newnode; return head; }
4.尾删
SListNode* SListPopBack(SListNode* head){ //1.空//2.只有一个节点 //3.有多个节点 if (head == NULL) {return head; } else if (head->_next== NULL) {free(head); head = NULL; return head; } else {SListNode* prev = NULL; SListNode* tail = head; while (tail->_next != NULL)//利用前指针来保存要删除的节点的前一个节点{prev = tail; tail = tail->_next; }free(tail); if (prev != NULL)prev->_next = NULL; return head; }}
5.头删
SListNode* SListPopFornt(SListNode* head){ if (head == NULL) {return head; } else {SListNode* cur = head->_next; free(head); head = cur; return head; }}
6.查找节点
SListNode* SListFind(SListNode* head, SLTDadaType x){ SListNode* cur = head; while (cur) {if (cur->_data =https://www.it610.com/article/= x){return cur; }else{cur = cur->_next; } } return NULL; }
7.修改
void SListModify(SListNode* head, SLTDadaType x, SLTDadaType y)//x修改{ SListNode* find = SListFind(head, x); if (find) {find->_data = https://www.it610.com/article/y; } else {printf("对不起,您要修改的值不存在\n"); }}
总结 本篇文章主要是针对单向链表一些基本操作的代码实现,若有写的错误或值得改进的地方,请大家多多留言指出。
最后,也请大家多多支持,求关注!!!
【C语言|C语言 单向链表的增删查改快速掌握】到此这篇关于C语言 单向链表的增删查改快速掌握的文章就介绍到这了,更多相关C语言 单向链表内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
推荐阅读
- 【生信技能树】R语言练习题|【生信技能树】R语言练习题 - 中级
- 一起来学习C语言的字符串转换函数
- C语言字符函数中的isalnum()和iscntrl()你都知道吗
- C语言浮点函数中的modf和fmod详解
- C语言中的时间函数clock()和time()你都了解吗
- leetcode|leetcode 92. 反转链表 II
- C语言学习|第十一届蓝桥杯省赛 大学B组 C/C++ 第一场
- C语言解方程的根和判断是否是闰年
- C语言的版本比较
- 【C】题目|【C语言】题集 of ⑥