List.h文件
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int LTDateType;
typedef struct ListNode
{
struct ListNode* prev;
struct ListNode* next;
LTDateType val;
}LTNode;
LTNode* Buy_Node(LTDateType x);
LTNode* LTInit();
void LTDestroy(LTNode* phead);
void LTPushFront(LTNode* phead, LTDateType x);
void LTPopFront(LTNode* phead);
void LTPushBack(LTNode* phead, LTDateType x);
void LTPopBack(LTNode* phead);
void LTPrint(LTNode* phead);
bool LTEmpty(LTNode* phead);
List.c文件
#include"List.h"
LTNode* Buy_Node(LTDateType x)
{
LTNode* node = (LTNode*)malloc(sizeof(LTNode));
if (node == NULL)
{
perror("malloc fail:");
return NULL;
}
node->next = NULL;
node->prev = NULL;
node->val = x;
return node;
}
LTNode* LTInit()
{
LTNode* phead = Buy_Node(-1);
phead->next = phead;
phead->prev = phead;
return phead;
}
void LTDestroy(LTNode* phead)
{
LTNode* cur = phead->next;
while (cur != phead)
{
LTNode* tmp = cur->next;
free(cur);
cur = tmp;
}
}
void LTPushBack(LTNode* phead, LTDateType x)
{
assert(phead);
LTNode* newnode = Buy_Node(x);
LTNode* tail = phead->prev;//找尾
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
}
void LTPushFront(LTNode* phead, LTDateType x)
{
assert(phead);
LTNode* newnode = Buy_Node(x);
LTNode* first = phead->next;//第一个节点
phead->next = newnode;
newnode->prev = phead;
newnode->next = first;
first->prev = newnode;
}
bool LTEmpty(LTNode* phead)
{
return phead->next == NULL;
}
void LTPopBack(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* tail = phead->prev;
LTNode* prev = tail->prev;
prev->next = phead;
phead->prev = prev;
free(tail);
tail = NULL;
}
void LTPopFront(LTNode* phead)
{
assert(phead);
assert(!LTEmpty(phead));
LTNode* front = phead->next;
LTNode* next = phead->next->next;
phead->next = next;
next->prev = phead;
free(front);
}
void LTPrint(LTNode* phead)
{
assert(phead);
printf("<-head->");
LTNode* cur = phead->next;
while (cur!=phead)
{
printf("%d <-> ", cur->val);
cur = cur->next;
}
puts("");
}
LTNode* find(LTNode* phead, LTDateType x)
{
LTNode* cur = phead->next;
while (cur != phead)
{
if (cur->val == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
//在pos前面插入
void LTInser(LTNode* pos, LTDateType x)
{
LTNode* newnode = Buy_Node(x);
LTNode* prev = pos->prev;
prev->next = newnode;
newnode->prev = prev;
newnode->next = pos;
pos->prev = newnode;
}
Test.c文件
#include"List.h"
void TestList1()
{
LTNode* plist = LTInit();
LTPushBack(plist, 1);
LTPushBack(plist, 2);
LTPushBack(plist, 3);
LTPushBack(plist, 4);
LTPushBack(plist, 5);
LTPrint(plist);
LTPopBack(plist);
LTPopBack(plist);
LTPrint(plist);
LTPushFront(plist, 100);
LTPushFront(plist, 50);
LTPushFront(plist, 10);
LTPrint(plist);
LTPopFront(plist);
LTPopFront(plist);
LTPrint(plist);
}
int main(void)
{
TestList1();
return 0;
}
![11]()