1.链表结构2.DList.h
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef int DListtype;
typedef struct DList
{
struct DList* prev;
struct DList* next;
DListtype val;
}DLNode;
DLNode* Buynode(DListtype x);//开辟新空间
DLNode* Initnode();//初始化函数
void Printnode(DLNode* phead);//打印函数
void Pushback(DLNode* phead,DListtype x);//尾插
void Popback(DLNode* phead);//尾删
void PushFront(DLNode* phead, DListtype x);//头插
void PopFront(DLNode* phead);//头删
DLNode* FindDLnode(DLNode* phead, DListtype x);//查找
void DLinsert(DLNode* pos, DListtype x);//指定位置前插入
void DLerase(DLNode* pos);//指定位置删除
void DLdestory(DLNode* phead);//销毁函数
3.DList.c
#include"DList.h"
DLNode* Buynode(DListtype x)
{
DLNode* node = (DLNode*)malloc(sizeof(DLNode));
if (node == NULL)
{
perror("malloc error:");
exit(-1);
}
node->val = x;
node->next = NULL;
node->prev = NULL;
return node;
}
DLNode* Initnode()
{
DLNode* phead = Buynode(-1);
phead->next = phead;
phead->prev = phead;
return phead;
}
void Printnode(DLNode* phead)
{
assert(phead);
DLNode* cur = phead->next;
while (cur!=phead)
{
printf("%d->", cur->val);
cur = cur->next;
}
printf("\n");
}
void Pushback(DLNode* phead, DListtype x)
{
DLNode* newnode = Buynode(x);
DLNode* tail = phead->prev;
tail->next = newnode;
newnode->prev = tail;
phead->prev = newnode;
newnode->next = phead;
}
void Popback(DLNode* phead)
{
assert(phead);
assert(phead->next != NULL);
DLNode* tail = phead->prev;
DLNode* tailPrev = tail->prev;
tailPrev->next = phead;
phead->prev = tailPrev;
free(tail);
}
void PushFront(DLNode* phead, DListtype x)
{
assert(phead);
DLNode* newnode = Buynode(x);
newnode->next = phead->next;
phead->next->prev = newnode;
phead->next = newnode;
newnode->prev = phead;
}
void PopFront(DLNode* phead)
{
assert(phead);
assert(phead->next!=NULL);
DLNode* head = phead->next;
DLNode* second = head->next;
phead->next = second;
second->prev = phead;
free(head);
}
DLNode* FindDLnode(DLNode* phead, DListtype x)
{
assert(phead);
DLNode* cur = phead->next;
while (cur != phead)
{
if (cur->val == x)
return cur;
else
cur = cur->next;
}
return NULL;
}
void DLinsert(DLNode* pos, DListtype x)
{
assert(pos);
DLNode* newnode = (DLNode*)malloc(sizeof(DLNode));
DLNode* Prev = pos->prev;
newnode->val = x;
pos->prev = newnode;
newnode->next = pos;
Prev->next = newnode;
newnode->prev = Prev;
}
void DLerase(DLNode* pos)
{
assert(pos);
DLNode* next = pos->next;
DLNode* prev = pos->prev;
prev->next = next;
next->prev = prev;
free(pos);
}
void DLdestory(DLNode* phead)
{
assert(phead);
DLNode* cur = phead->next;
while (cur != phead)
{
DLNode* next = cur->next;
free(cur);
cur = next;
}
free(phead);
}