双向链表的实现

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;
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

甘-

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值