DoublyList.h
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
typedef int DataType;
typedef struct DoublyList
{
DataType val;
struct DoublyList* prev;
struct DoublyList* next;
}DouList;
//初始化链表
void InitList(DouList** phead);
//打印链表
void PrintList(DouList* phead);
//创建新节点
DouList* NewNode(DataType n);
//尾插节点
void PushBack(DouList* phead, DataType n);
//尾删节点
void PopBack(DouList* phead);
//头插节点
void PushFront(DouList* phead, DataType n);
//头删节点
void PopFront(DouList* phead);
//销毁链表
void DestroyList(DouList** phead);
DoublyLis.c
#define _CRT_SECURE_NO_WARNINGS 1
#include "DoublyList.h"
void InitList(DouList** phead)
{
DouList* tail = *phead;
tail = (DouList*)malloc(sizeof(DouList));
if (tail == NULL)
{
perror(tail);
exit(-1);
}
tail->next = tail;
tail->prev = tail;
tail->val = 0;
}
void PrintList(DouList* phead)
{
assert(phead);
DouList* tail = phead->next;
if (tail == phead)
{
printf("链表中无节点\n");
return;
}
while (tail != phead)
{
printf("%d-> ", tail->val);
tail = tail->next;
}
printf("\n");
}
DouList* NewNode(DataType n)
{
DouList* newnode = (DouList*)malloc(sizeof(DouList));
if (NULL == newnode)
{
perror(newnode);
exit(-1);
}
newnode->next = NULL;
newnode->prev = NULL;
newnode->val = n;
return newnode;
}
void PushBack(DouList* phead, DataType n)
{
assert(phead);
DouList* newnode = NewNode(n);
DouList* tail = phead->prev;
phead->prev = newnode;
tail->next = newnode;
newnode->prev = tail;
newnode->next = phead;
}
void PopBack(DouList* phead)
{
assert(phead);
DouList* tail = phead->prev;
if (tail == phead)
{
printf("链表中无节点\n");
return;
}
DouList* cur = tail->prev;
cur->next = phead;
phead->prev = cur;
free(tail);
tail = NULL;
}
void PushFront(DouList* phead, DataType n)
{
assert(phead);
DouList* newnode = NewNode(n);
DouList* tail = phead->next;
phead->next = newnode;
tail->prev = newnode;
newnode->prev = phead;
newnode->next = tail;
}
void PopFront(DouList* phead)
{
assert(phead);
DouList* tail = phead->next;
if (tail == phead)
{
printf("链表中无节点\n");
return;
}
DouList* cur = tail->next;
phead->next = cur;
cur->prev = phead;
free(tail);
tail = NULL;
}
void DestroyList(DouList** phead)
{
assert(*phead);
DouList* tail = (*phead)->next;
DouList* cur = tail;
while (cur != *phead)
{
cur = cur->next;
free(tail);
tail = cur;
}
free(*phead);
*phead = NULL;
}