不一一介绍了 直接上代码
目录
初始化
struct ListNode* InitDlist()//双向链表的初识化
{
struct ListNode* pHead=BuyDList(0);
pHead->next = pHead;
pHead->prev = pHead;
return pHead;
}
创建结点
struct ListNode* BuyDList(DlistType x)//创建新结点
{
struct ListNode* newnode = (struct ListNode*)malloc(sizeof(struct ListNode));
newnode->prev = NULL;
newnode->next = NULL;
newnode->val = x;
return newnode;
}
打印链表
void printDlist(struct ListNode* head)//打印
{
struct ListNode* next = head->next;
while (next != head)
{
printf("%d->", next->val);
next = next->next;
}
printf("over\n");
}
头插
void PushFront(struct ListNode* head, DlistType x)//头插
{
struct ListNode* newnode = BuyDList(x);//创建新结点
struct ListNode* first = head->next;//保存除哨兵位的第一个存有数据的结点
newnode->next =first;//四步操作让新节点插入原链表 两个方向都是双向 方向要变换四次
newnode->prev = head;
head->next = newnode;
first->prev = newnode;
}
头删
void PopBack(struct ListNode* head)//尾删
{
assert(head);
assert(head->next!=head);
struct ListNode* tail = head->prev;
struct ListNode* tailprev = tail->prev;
free(tail);
tailprev->next = head;
head->prev = tailprev;
}
尾插
void PushFront(struct ListNode* head, DlistType x)//头插
{
struct ListNode* newnode = BuyDList(x);//创建新结点
struct ListNode* first = head->next;//保存除哨兵位的第一个存有数据的结点
newnode->next =first;//四步操作让新节点插入原链表 两个方向都是双向 方向要变换四次
newnode->prev = head;
head->next = newnode;
first->prev = newnode;
}
尾删
void PopBack(struct ListNode* head)//尾删
{
assert(head);
assert(head->next!=head);
struct ListNode* tail = head->prev;
struct ListNode* tailprev = tail->prev;
free(tail);
tailprev->next = head;
head->prev = tailprev;
}
定向插入(前)
void DListInsertFront(struct ListNode* head, DlistType x, DlistType k)//指定位置前插
{
assert(head);
struct ListNode* insert = FindNode(head, x);
if (insert)
{
struct ListNode* newnode = BuyDList(k);
struct ListNode* prev = insert->prev;
prev->next = newnode;
newnode->prev = prev;
newnode->next = insert;
insert->prev = newnode;
}
}
定向插入(后)
void DListInsertBehind(struct ListNode* head, DlistType x, DlistType k)//指定位置后插
{
assert(head);
struct ListNode* insert = FindNode(head, x);
if (insert)
{
struct ListNode* newnode = BuyDList(k);
struct ListNode* next = insert->next;
newnode->val = k;
newnode->next = next;
next->prev = newnode;
newnode->prev = insert;
insert->next = newnode;
}
}
删除
void DListErase(struct ListNode* head, DlistType x)//删除指定结点
{
assert(head);
assert(head->next != head);
struct ListNode* erase = FindNode(head, x);
if (erase)
{
struct ListNode* next = erase->next;
struct ListNode* prev = erase->prev;
free(erase);
next->prev = prev;
prev->next = next;
}
}
修改
void DListModify(struct ListNode* head, DlistType x, DlistType k)
{
assert(head);
struct ListNode* modify = FindNode(head, x);
modify->val = k;
}