头文件部分
头文件部分代码包含了必要的头文件引用以及该链表所需的所有接口函数
#pragma once
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
using namespace std;
typedef int Type;
typedef struct ListNode
{
Type data;
struct ListNode* next;
struct ListNode* prev;
}LN;
LN* ListInit();
LN* BuyListNode(Type x);
void ListPrint(LN* phead);
void ListDestroy(LN* phead);
void ListPushBack(LN* phead,Type x);
void ListPopBack(LN* phead);
void ListPushFront(LN* phead, Type x);
void ListPopFront(LN* phead);
LN* ListFind(LN* phead, Type x);
void ListInsert(LN* pos, Type x);
void ListErase(LN* pos);
源文件接口函数实现部分
源文件部分包括对头文件中所有的接口函数具体的代码实现
#include"List.h"
LN* ListInit()
{
LN* phead = (LN*)malloc(sizeof(LN));
phead->next = phead;
phead->prev = phead;
return phead;
}
LN* BuyListNode(Type x)
{
LN* newnode = (LN*)malloc(sizeof(LN));
newnode->data = x;
newnode->next = NULL;
newnode->prev = NULL;
return newnode;
}
void ListPushBack(LN* phead,Type x)
{
assert(phead);
LN* tail = phead->prev;
LN* newnode = BuyListNode(x);
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
phead->prev = newnode;
newnode = tail;
}
void ListPrint(LN* phead)
{
assert(phead);
LN* cur = phead->next;
while (cur != phead)
{
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
void ListPopBack(LN* phead)
{
LN* tail = phead->prev->prev;
assert(phead);
assert(phead->next != phead);
free(phead->prev);
phead->prev = NULL;
tail->next = phead;
phead->prev = tail;
}
void ListPushFront(LN* phead, Type x)
{
assert(phead);
LN* cur = phead->next;
LN* newnode = BuyListNode(x);
newnode->data = x;
newnode->next = cur;
cur->prev = newnode;
newnode->prev = phead;
phead->next = newnode;
}
void ListPopFront(LN* phead)
{
assert(phead);
assert(phead->next != phead);
LN* cur = phead->next;
LN* head = cur->next;
free(cur);
cur = NULL;
phead->next = head;
head->prev = phead;
}
LN* ListFind(LN* phead, Type x)
{
assert(phead);
LN* cur = phead->next;
while (cur != phead)
{
if (cur->data == x)
{
return cur;
}
cur = cur->next;
}
return NULL;
}
//pos位置之前插入
void ListInsert(LN* pos, Type x)
{
assert(pos);
LN* posPrev = pos->prev;
LN* newnode = BuyListNode(x);
posPrev->next = newnode;
newnode->prev = posPrev;
newnode->next = pos;
pos->prev = newnode;
}
//删除pos位置
void ListErase(LN* pos)
{
assert(pos);
LN* posPrev = pos->prev;
LN* posNext = pos->next;
posPrev->next = posNext;
posNext->prev = posPrev;
free(pos);
pos = NULL;
}
void ListDestroy(LN* phead)
{
assert(phead);
LN* cur = phead->next;
while (cur != phead)
{
LN* next = cur->next;
free(cur);
cur = next;
}
free(phead);
phead = NULL;
}
源文件主函数测试部分
该文件主要用于对前面所写代码的验证以及对该链表的具体功能实现
#include"List.h"
void Test01()
{
LN* plist = ListInit();
ListPushBack(plist, 1);
ListPushBack(plist, 2);
ListPushBack(plist, 3);
ListPushBack(plist, 4);
ListPrint(plist);
ListPopBack(plist);
ListPrint(plist);
ListPushFront(plist, 7);
ListPrint(plist);
ListPopFront(plist);
ListPrint(plist);
ListFind(plist, 3);
//按照具体需求调用接口函数
}
int main()
{
Test01();
system("pause");
return 0;
}