目录
1. List.h头文件
2. List.c源文件
3. main.c源文件
4. 运行截图

目录
1. List.h头文件
2. List.c源文件
3. main.c源文件
4. 运行截图
#pragma once #include#include typedef int NodeDate; typedef struct Node { NodeDate Data; struct Node* prev; //指向前一个节点 struct Node* next; //指向后一个节点 }Node; Node* InitList(); void PrintList(Node* phead); //打印链表 void FrontPush(Node* phead, NodeDate x); void BackPush(Node* phead, NodeDate x); void FrontPop(Node* phead); void BackPop(Node* phead); void InsertNode(Node* pos, NodeDate x); //在pos节点之前插入一个节点 void EraseNode(Node* pos); //删除pos节点 void DestoryList(Node* phead); //销毁链表 Node* FindNode(Node* phead, NodeDate x);
#include "List.h"
Node* BuyNode()
{
Node* new = (Node*)malloc(sizeof(Node));
new->next = NULL;
new->prev = NULL;
return new;
}
Node* InitList()
{
Node* node = BuyNode();
node->next = node;
node->prev = node;
}
void PrintList(Node* phead)
{
assert(phead);
Node* cur = phead->next;
if (cur == phead)
{
printf("list is empty");
}
while (cur != phead)
{
printf("%d ", cur->Data);
cur = cur->next;
}
printf("n");
}
void FrontPush(Node* phead, NodeDate x)
{
assert(phead);
InsertNode(phead->next, x);
}
void BackPush(Node* phead, NodeDate x)
{
assert(phead);
InsertNode(phead, x);
}
void FrontPop(Node* phead)
{
assert(phead);
printf("FrontPop once: ");
EraseNode(phead->next);
}
void BackPop(Node* phead)
{
assert(phead);
printf("BackPop once: ");
EraseNode(phead->prev);
}
void InsertNode(Node* pos, NodeDate x)
{
assert(pos);
Node* new = BuyNode();
new->Data = x;
Node* prev = pos->prev;
prev->next = new;
new->prev = prev;
new->next = pos;
pos->prev = new;
}
void EraseNode(Node* pos)
{
assert(pos);
if (pos->next == pos)
{
printf("Delete failed, list is emptyn");
return;
}
pos->prev->next = pos->next;
pos->next->prev = pos->prev;
free(pos);
pos = NULL;
printf("EraseNode once: ");
}
void DestoryList(Node* phead)
{
assert(phead);
Node* cur = phead->next;
while (cur != phead)
{
Node* next = cur->next;
EraseNode(cur);
cur = next;
}
printf("list is destoryn");
}
Node* FindNode(Node* phead, NodeDate x)
{
Node* cur = phead->next;
while (cur != phead)
{
if (cur->Data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
#include "List.h"
void Test1()
{
Node* head = InitList();
FrontPush(head, 1);
FrontPush(head, 2);
FrontPush(head, 3);
FrontPush(head, 4);
FrontPush(head, 5);
printf("FrontPush 1~5:");
PrintList(head);
EraseNode(FindNode(head, 3));
PrintList(head);
FrontPop(head);
PrintList(head);
BackPop(head);
PrintList(head);
BackPop(head);
PrintList(head);
BackPop(head);
PrintList(head);
BackPop(head);
PrintList(head);
printf("n");
}
void Test2()
{
Node* head = InitList();
BackPush(head, 1);
BackPush(head, 2);
BackPush(head, 3);
BackPush(head, 4);
BackPush(head, 5);
printf("BackPush 1~5:");
PrintList(head);
DestoryList(head);
PrintList(head);
printf("n");
}
int main()
{
Test1();
Test2();
return 0;
}