这篇“C++双向链表的增删查改操作方法源码分析”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“C++双向链表的增删查改操作方法源码分析”文章吧。
一、什么是双链表
双向链表也叫双链表,是链表的一种,它是单链表的升级版,与单链表不同的是,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。而单链表只有一个指针,指向后继。
双链表示意图
首先创立一个结构体,其中包含一个prev指针,一个val值以及一个next指针。如图可以看出其中prev指针指向的是上一个结构体,而next指针指向的是下一个结构体。结构体代码
typedef int LTDataType;
typedef struct ListNode
{
LTDataType _data;
struct ListNode* _next;
struct ListNode* _prev;
}ListNode;二、双链表功能函数
1、创建返回链表的头结点
ListNode* ListCreate()
{
ListNode* guard = (ListNode*)malloc(sizeof(ListNode));
if (guard == NULL)
{
perror("ListCreate");
exit(-1);
}
guard->_next = guard;
guard->_prev = guard;
return guard;
}2、双向链表打印
void ListPrint(ListNode* pHead)
{
assert(pHead);
ListNode* cur = pHead;
while (cur->_next != pHead)
{
cur = cur->_next;
printf("%d->", cur->_data);
}
printf("NULL
");
return;
}3、双向链表尾插
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;
}4、双向链表尾删
void ListPopBack(ListNode* pHead)
{
assert(pHead);
ListNode* pre = pHead->_prev->_prev;
free(pHead->_prev);
pre->_next = pHead;
pHead->_prev = pre;
return;
}5、双向链表头插
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;
}6、双向链表头删
void ListPopFront(ListNode* pHead)
{
assert(pHead);
ListNode* cur = pHead->_next->_next;
free(pHead->_next);
pHead->_next = cur;
cur->_prev = pHead;
return;
}7、双向链表查找
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.
");
return NULL;
}8、双向链表在pos的前面进行插入
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;
}9、双向链表删除pos位置的节点
void ListErase(ListNode* pos)
{
ListNode* front = pos->_prev;
ListNode* behind = pos->_next;
free(pos);
front->_next = behind;
behind->_prev = front;
return;
}10、双向链表销毁
void ListDestory(ListNode* pHead)
{
assert(pHead);
while (pHead->_next != pHead)
{
pHead->_next = pHead->_next->_next;
free(pHead->_next->_prev);
pHead->_next->_prev = pHead;
}
return;
}