带头节点双向循环链表
双向循环的节点由三部分构成,prev指针指向链表前一个节点,next指针指向后一个节点,data区储存节点数据。
双向循环链表结构看起来复杂,但简化了链表的插入删除等各种操作。
定义节点
typedef struct ListNode
{
DataType data;
struct ListNode* next;
struct ListNode* prev;
}ListNode;
创建头节点
ListNode* ListCreate()
{
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
if (head == NULL)
return NULL;
head->next = head;
head->prev = head;
head->data = 0;
return head;
}
双向链表的销毁
void ListDestory(ListNode* pHead)
{
assert(pHead);
ListNode* p= pHead->next;
while (p!=pHead)
{
pHead->next = p->next;
free(p);
p = pHead->next;
}
//删除头节点
free(pHead);
pHead=NULL;
}
双向链表头插
void ListPushBack(ListNode* pHead, DataType x)
{
assert(pHead);
ListNode* p = pHead;
ListNode* s = (ListNode*)malloc(sizeof(ListNode));
if (s == NULL)
return;
s->data = x;
s->prev = p->prev;
s->next = p;
p->prev->next = s;
p->prev = s;
}
双向链表头删
void ListPopFront(ListNode* pHead)
{
ListNode* p = pHead->next;
p->next->prev = pHead;
pHead->next = p->next;
free(p);
}
双向链表尾插
void ListPushBack(ListNode* pHead, DataType x)
{
assert(pHead);
ListNode* p = pHead->prev;//获取链表的尾节点
ListNode* s = (ListNode*)malloc(sizeof(ListNode));
if (s == NULL)
return;
s->data = x;
s->prev = p;
s->next = pHead;
p->next = s;
pHead->prev = s;
}
双向链表尾删
void ListPopBack(ListNode* pHead)
{
ListNode* p = pHead->prev;
p->prev->next = pHead;
pHead->prev = p->prev;
free(p);
}
双向链表的查找
void ListInsert(ListNode* pos, DataType x)
{
ListNode* s = (ListNode*)malloc(sizeof(ListNode));
if (s == NULL)
return;
s->data = x;
s->next = pos->next;
s->prev = pos;
pos->next->prev = s;
pos->next = s;
}
删除pos后的节点
void ListErase(ListNode* pos)
{
assert(pos);
ListNode* p = pos->next;
pos->next = p->next;
p->next->prev = pos;
free(p);
}