首先看一下要用到的函数
#pragma once
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int LTDataType;
typedef struct ListNode
{
struct ListNode* next;
struct ListNode* prev;
LTDataType data;
}LTNode;
bool LTEmpty(LTNode* phead);//判断链表是否为空
LTNode* LTInit();//链表的初始化
void LTPushBack(LTNode* phead, LTDataType x);//链表的尾插
LTNode* BuyLTNode(LTDataType x);//创建新链表
void LTPrint(LTNode* phead);//链表的打印
void LTPopBack(LTNode* phead);//链表的尾删
void LTPopFront(LTNode* phead);//链表的头插
LTNode* LTFind(LTNode* phead, LTDataType x);//链表的搜索
void LTInsert(LTNode* pos, LTDataType x);//pos之前插入
void LTErase(LTNode* pos, LTDataType x);//链表pos位置删除
void LTDestory(LTNode* phead);//链表的删除
接下来看一下每个函数的实现
首先是链表节点的创建
LTNode* BuyLTNode(LTDataType x)
{
LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
if (newnode == NULL)
{
perror("malloc fail");
return NULL;
}
newnode->data = x;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
判断链表是否为空
bool LTEmpty(LTNode* phead)
{
assert(phead);
return phead->next == phead;
}
初始化链表
LTNode* LTInit()
{
LTNode* phead = BuyLTNode(-1);
phead->next = phead;
phead->prev = phead;
return phead;
}
链表的尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* tail = phead->prev;
LTNode* newnode = BuyLTNode(x);
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
}
链表的头插
void LTPushFront(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* newnode = BuyLTNode(x);
newnode->next = phead->next;
phead->next->prev = newnode;
phead->next = newnode;
newnode->prev = phead;
}
链表的头删
void LTPopFront(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* first=phead->next;
LTNode* second = first->next;
phead->next = second;
second->prev = phead;
free(first);
}
链表的尾删
void LTPopBack(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* tail = phead->prev;
LTNode* tailPrev = tail->prev;
free(tail);
tailPrev->next = phead;
phead->prev = tailPrev;
}
链表的打印
void LTPrint(LTNode* phead)
{
assert(phead);
printf("head<==>");
LTNode* cur = phead->next;
while (cur!=phead)
{
printf("%d<==>", cur->data);
cur = cur->next;
}
printf("\n");
}
链表的查找
LTNode* LTFind(LTNode* phead, LTDataType x)
{
assert(phead);
LTNode* cur = phead->next;
while (cur!=phead)
{
if (cur->data == x)
{
return cur;
}
}
return NULL;
}
链表的任意位置插入
void LTInsert(LTNode* pos, LTDataType x)
{
assert(pos);
LTNode* prev = pos->prev;
LTNode* newnode = BuyLTNode(x);
prev->next = newnode;
newnode->prev = prev;
newnode->next = pos;
pos->prev = newnode;
}
链表的任意位置删除
void LTErase(LTNode* pos, LTDataType x)
{
assert(pos);
LTNode* posPrev = pos->prev;
LTNode* posNext = pos->next;
posPrev->next = posNext;
posNext->prev = posPrev;
free(pos);
}
链表的销毁
void LTDestory(LTNode* phead)
{
assert(phead);
LTNode* cur = phead->next;
while (cur != phead)
{
LTNode* next = cur->next;
free(cur);
cur = next;
}
free(phead);
}