List.h
#pragma once
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <errno.h>
typedef int LDataType;
typedef struct ListNode
{
LDataType data;
struct ListNode* pre;
struct ListNode* next;
}LNode;
LNode* LInit();//链表的初始化
void LPushBack(LNode* phead, LDataType x);//双向链表的尾插
void LPushFront(LNode* phead, LDataType x);//双向链表的头插
LNode* LPopBack(LNode* phead);//双向链表的尾删
LNode* LPopFront(LNode* phead);//双向链表的头删
LNode* LFind(LNode* phead, LDataType x);//双向链表的查找
void LInsert(LNode* pos, LDataType x);//在pos之前插入
void LErase(LNode* pos);//删除pos位置的结点
void LDestroy(LNode* phead);//销毁链表
List.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"
void Print(LNode* phead)
{
LNode* p = phead->next;
while (p != phead)
{
printf("%d<=>", p->data);
p = p->next;
}
printf("NULL\n");
}
LNode* ByNode(LDataType x)
{
LNode* ptr = (LNode*)malloc(sizeof(LNode));
if (ptr == NULL)
{
perror("ByNode Fail::");
return;
}
ptr->pre = NULL;
ptr->next = NULL;
ptr->data = x;
return ptr;
}
LNode* LInit()
{
LNode* phead = ByNode(-1);
phead->next = phead;
phead->pre = phead;
return phead;
}
void LPushBack(LNode* phead, LDataType x)
{
assert(phead);
LNode* newnode = ByNode(x);
LNode* tail = phead->pre;
tail->next = newnode;
newnode->pre = tail;
newnode->next = phead;
phead->pre = newnode;
tail = newnode;
}
void LPushFront(LNode* phead, LDataType x)
{
assert(phead);
LNode* newnode = ByNode(x);
newnode->next = phead->next;
phead->next->pre = newnode;
newnode->pre = phead;
phead->next = newnode;
}
void LErase(LNode* pos)
{
assert(pos);
pos->pre->next = pos->next;
pos->next->pre = pos->pre;
free(pos);
}
LNode* LPopBack(LNode* phead)
{
assert(phead);
/*
LNode* tail = phead->pre;
phead->pre = tail->pre;
tail->next = NULL;
tail->pre->next = phead;
tail->pre = NULL;
free(tail);
tail = phead->pre;
*/
LErase(phead->pre);
}
LNode* LPopFront(LNode* phead)
{
assert(phead);
//LNode* next = phead->next;
//phead->next = next->next;
//phead->next->pre = phead;
只需要修改两个指针即可,剩下的两个next的指针会直接随着next的free消失。
//free(next);
LErase(phead -> next);
}
LNode* LFind(LNode* phead, LDataType x)
{
assert(phead);
LNode* cur = phead->next;
while (cur!=phead)
{
if (cur->data == x)
return cur;
cur = cur->next;
}
return NULL;
}
void LInsert(LNode* pos, LDataType x)
{
assert(pos);
LNode* pre = pos->pre;
LNode* newnode = ByNode(x);
newnode->next = pos;
pos->pre = newnode;
pre->next = newnode;
newnode->pre = pre;
}
void LDestroy(LNode* phead)
{
LNode* cur = phead->next;
while (phead->next!=phead)
{
LErase(phead->next);
}
}
test.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"
void test1()
{
LNode* plist = LInit();
LPushBack(plist, 0);
LPushBack(plist, 7);
LPushBack(plist, 2);
LPushBack(plist, 0);
LPopBack(plist);
LPopFront(plist);
Print(plist);
LDestroy(plist);
Print(plist);
}
int main()
{
test1();
return 0;
}