List.h
#define _CRT_SECURE_NO_WARNINGS 1
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<stdbool.h>
typedef int LTDataType;
//带头双向循环链表
typedef struct ListNode
{
struct ListNode* next;
struct ListNode* prev;
LTDataType data;
}LTNode;
//链表打印
void ListPrint(LTNode* phead);
//开辟新节点
LTNode* BuyListNode(LTDataType x);
//链表初始化
void ListInit(LTNode** pphead);
//链表摧毁
void ListDestroy(LTNode* phead);
//链表判断是否为空
bool ListEmpty(LTNode* phead);
//链表大小
size_t ListSize(LTNode* phead);
//链表尾插
void ListPushBack(LTNode* phead, LTDataType x);
//链表头插
void ListPushFront(LTNode* phead, LTDataType x);
//链表尾删
void ListPopBack(LTNode* phead);
//链表头删
void ListPopFront(LTNode* phead);
//查找节点
LTNode* ListFind(LTNode* phead, LTDataType x);
//删除某个节点
void ListErase(LTNode* pos);
//链表插入
void ListInsert(LTNode* pos, LTDataType x);
List.c
#define _CRT_SECURE_NO_WARNINGS 1
#include"List.h"
bool ListEmpty(LTNode* phead)
{
assert(phead);
if (phead->next == phead)
return true;
else
return false;
}
size_t ListSize(LTNode* phead)
{
assert(phead);
int sz = 0;
//从哨兵位的下一个节点开始遍历
LTNode* cur = phead->next;
while (cur != phead)
{
sz++;
cur = cur->next;
}
return sz;
}
LTNode* BuyListNode(LTDataType x)
{
LTNode* node = (LTNode*)malloc(sizeof(LTNode));
if (NULL == node)
{
printf("malloc fail\n");
exit(-1);
}
node->next = NULL;
node->next = NULL;
node->data = x;
return node;
}
void ListInit(LTNode** pphead)
{
(*pphead) = BuyListNode(-1);
(*pphead)->next = *pphead;
(*pphead)->prev = *pphead;
}
void ListPrint(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
}
//在指定位置之前插入节点
void ListInsert(LTNode* pos, LTDataType x)
{
assert(pos);
LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
LTNode* prev = pos->prev;
newnode->next = pos;
newnode->prev = prev;
newnode->data = x;
prev->next = newnode;
pos->prev = newnode;
}
void ListPushBack(LTNode* phead, LTDataType x)
{
assert(phead);
ListInsert(phead, x);
}
void ListPushFront(LTNode* phead, LTDataType x)
{
assert(phead);
ListInsert(phead->next, x);
}
LTNode* ListFind(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
if (cur->data == x)
return cur;
cur = cur->next;
}
return NULL;
}
void ListDestroy(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
LTNode* next = cur->next;
free(cur);
cur = NULL;
cur = next;
}
phead->next = NULL;
phead->prev = NULL;
phead->data = -1;
}
void ListErase(LTNode* pos)
{
assert(pos);
LTNode* prev = pos->prev;
LTNode* next = pos->next;
prev->next = pos->next;
next->prev = pos->prev;
free(pos);
pos = NULL;
}
void ListPopBack(LTNode* phead)
{
assert(phead);
ListErase(phead->prev);
}
void ListPopFront(LTNode* phead)
{
assert(phead);
ListErase(phead);
}