脚本宝典收集整理的这篇文章主要介绍了【C语言】一篇文章带你彻底了解单向链表的增删查改,脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
链表是线性表的链式存储结构,它可以以O(1)的@R_546_1304@进行插入或者删除,同时由于是链式结构相比顺序表而言,不会存在空间浪费的情况。而链表又分为带头单向链表,不带头单向链表,带头循环链表,不带头循环链表,带头双向循环链表,不带头双向循环链表,带头双向链表,不带头双向链表,总共有八种,其中结构最简单的是不带头单向链表,也是实现起来最容易出错的。并且我们在网上进行链表的oj时,题目基本也是不带头的单向链表,而且也是互联网大厂面试中最容易考的。
tyPEdef int SLTDadaType;//存放的数据类型
struct SListNode
{
SLTDadaType _data;//存放的数据
struct SListNode* _next;//指向下一个节点的指针
};
typedef struct SListNode SListNode;
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修改
SListNode* BuyListNode(SLTDadaType x)
{
SListNode* newnode = (SListNode*)malloc(sizeof(SListNode));
newnode->_data = x;
newnode->_next = NULL;
return newnode;
}
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;
}
}
SListNode* SListPushFornt(SListNode* head, SLTDadaType x)
{
SListNode* newnode = BuyListNode(x);
newnode->_next = head;
head = newnode;
return head;
}
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;
}
}
SListNode* SListPopFornt(SListNode* head)
{
if (head == NULL)
{
return head;
}
else
{
SListNode* cur = head->_next;
free(head);
head = cur;
return head;
}
}
SListNode* SListFind(SListNode* head, SLTDadaType x)
{
SListNode* cur = head;
while (cur)
{
if (cur->_data == x)
{
return cur;
}
else
{
cur = cur->_next;
}
}
return NULL;
}
void SListModify(SListNode* head, SLTDadaType x, SLTDadaType y)//x修改
{
SListNode* find = SListFind(head, x);
if (find)
{
find->_data = y;
}
else
{
printf("对不起,您要修改的值不存在n");
}
}
本篇文章主要是针对单向链表一些基本操作的代码实现,若有写的错误或值得改进的地方,请大家多多留言指出。
最后,也请大家多多支持,求关注!!!
以上是脚本宝典为你收集整理的【C语言】一篇文章带你彻底了解单向链表的增删查改全部内容,希望文章能够帮你解决【C语言】一篇文章带你彻底了解单向链表的增删查改所遇到的问题。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。