这篇“C++双向链表的增删查改操作方法源码分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“C++双向链表的增删查改操作方法源码分析”文章吧。
双向链表也叫双链表,是链表的一种,它是单链表的升级版,与单链表不同的是,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。而单链表只有一个指针,指向后继。
双链表示意图
首先创立一个结构体,其中包含一个prev指针,一个val值以及一个next指针。如图可以看出其中prev指针指向的是上一个结构体,而next指针指向的是下一个结构体。结构体代码
typedef int LTDataType;
typedef struct ListNode
{
LTDataType _data;
struct ListNode* _next;
struct ListNode* _prev;
}ListNode;
ListNode* ListCreate()
{
ListNode* guard = (ListNode*)malloc(sizeof(ListNode));
if (guard == NULL)
{
perror("ListCreate");
exit(-1);
}
guard->_next = guard;
guard->_prev = guard;
return guard;
}
void ListPrint(ListNode* pHead)
{
assert(pHead);
ListNode* cur = pHead;
while (cur->_next != pHead)
{
cur = cur->_next;
printf("%d->", cur->_data);
}
printf("NULL\n");
return;
}
void ListPushBack(ListNode* pHead, LTDataType x)
{
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
if (newnode == NULL)
{
perror("ListPushBack");
exit(-1);
}
newnode->_data = x;
ListNode* cur = pHead->_prev;
newnode->_next = pHead;
newnode->_prev = cur;
cur->_next = newnode;
pHead->_prev = newnode;
return;
}
void ListPopBack(ListNode* pHead)
{
assert(pHead);
ListNode* pre = pHead->_prev->_prev;
free(pHead->_prev);
pre->_next = pHead;
pHead->_prev = pre;
return;
}
void ListPushFront(ListNode* pHead, LTDataType x)
{
assert(pHead);
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
if (newnode == NULL)
{
perror("ListPushFront");
exit(-1);
}
newnode->_data = x;
newnode->_next = pHead->_next;
newnode->_prev = pHead;
pHead->_next = newnode;
newnode->_next->_prev = newnode;
return;
}
void ListPopFront(ListNode* pHead)
{
assert(pHead);
ListNode* cur = pHead->_next->_next;
free(pHead->_next);
pHead->_next = cur;
cur->_prev = pHead;
return;
}
ListNode* ListFind(ListNode* pHead, LTDataType x)
{
assert(pHead);
ListNode* cur = pHead;
while (cur->_next != pHead)
{
cur = cur->_next;
if (cur->_data == x)
return cur;
}
printf("Can't find.\n");
return NULL;
}
void ListInsert(ListNode* pos, LTDataType x)
{
assert(pos);
ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
if (newnode == NULL)
{
perror("ListPushFront");
exit(-1);
}
ListNode* cur = pos->_prev;
newnode->_next = pos;
newnode->_prev = cur;
pos->_prev = newnode;
cur->_next = newnode;
return;
}
void ListErase(ListNode* pos)
{
ListNode* front = pos->_prev;
ListNode* behind = pos->_next;
free(pos);
front->_next = behind;
behind->_prev = front;
return;
}
void ListDestory(ListNode* pHead)
{
assert(pHead);
while (pHead->_next != pHead)
{
pHead->_next = pHead->_next->_next;
free(pHead->_next->_prev);
pHead->_next->_prev = pHead;
}
return;
}
以上就是关于“C++双向链表的增删查改操作方法源码分析”这篇文章的内容,相信大家都有了一定的了解,希望小编分享的内容对大家有帮助,若想了解更多相关的知识内容,请关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。
原文链接:https://blog.csdn.net/lllrx_/article/details/128472836