双向带头循环链表

头结点:date无意义的一个节点
头文件实现
#pragma once//防止头文件重定义

#include
#include
#include

typedef int DataType;

typedef struct CLinkList{
	DataType data;
	struct CLinkList *pPrev;
	struct CLinkList *pNext;
}CLinkList;

//初始化
void CInit(CLinkList **ppHead);

//尾插
void PushBack(CLinkList *pHead, DataType data);

//头插
void PushFront(CLinkList *pHead, DataType data);

//尾删
void PopBack(CLinkList *pHead);

//头删
void PopFront(CLinkList *pHead);

//清空
void Clear(CLinkList *pHead);

//销毁
void Destroy(CLinkList *pHead);
源文件实现
#include "CLinkList.h"

CLinkList * CreateNewNode(DataType data)
{
	CLinkList *pNode = (CLinkList *)malloc(sizeof(CLinkList));
	assert(pNode);
	pNode->data = data;
	return pNode;
}

//初始化
void CInit(CLinkList **ppHead)
{
	(*ppHead) = CreateNewNode(0);//初始化头结点时,可赋值为0也可不赋值
	(*ppHead)->pNext = *ppHead;
	(*ppHead)->pPrev = *ppHead;
}

//尾插
void PushBack(CLinkList *pHead, DataType data)
{
	CLinkList *pNode = CreateNewNode(data);
	pNode->pPrev = pHead->pPrev;
	pNode->pNext = pHead;

	pHead->pPrev->pNext = pNode;
	pHead->pPrev = pNode;
}
//头插
void PushFront(CLinkList *pHead, DataType data)
{
	CLinkList *pNode = CreateNewNode(data);
	pNode->pPrev = pHead;
	pNode->pNext = pHead->pNext;

	pHead->pNext->pPrev = pNode;
	pHead->pNext = pNode;
}

//尾删
void PopBack(CLinkList *pHead)
{
	assert(pHead->pNext);

	CLinkList *pNode = pHead->pPrev;
	pHead->pPrev = pHead->pPrev->pPrev;
	pHead->pPrev->pNext = pHead;
	free(pNode);
}

//头删
void PopFront(CLinkList *pHead)
{
	assert(pHead->pNext);
	
	CLinkList *pNode = pHead->pNext;
	pHead->pNext = pNode->pNext;
	pNode->pNext->pPrev = pHead;
}

//清空
void Clear(CLinkList *pHead)
{
	assert(pHead);

	CLinkList *pNode = pHead;
	while (pNode->pNext != pHead){
		pNode->pNext->data = 0;
		pNode = pNode->pNext;
	}
}

//销毁
void Destroy(CLinkList *pHead)
{
	assert(pHead);

	CLinkList *pNode = pHead;
	CLinkList *pOld = pNode;
	while (pNode->pNext != pHead){
		pOld = pNode;
		pNode = pNode->pNext;
		free(pOld);
	}
	free(pNode);
}

void Print(CLinkList *pHead)
{
	CLinkList *pNode = pHead;
	while (pNode->pNext != pHead){//不输出头结点无意义
		printf("%d ", pNode->pNext->data);
		pNode = pNode->pNext;
	}
	printf("\n");
}

int main()
{
	CLinkList *pHead;
	CInit(&pHead);//要改变pHead就传地址
	//pHead是一个date没有意义的头结点

	PushBack(pHead, 1);
	PushBack(pHead, 2);
	Print(pHead);

	PushFront(pHead, 3);
	PushFront(pHead, 4);
	Print(pHead);

	PopBack(pHead);
	Print(pHead);
	PopFront(pHead);
	Print(pHead);

	Clear(pHead);
	Print(pHead);

	system("pause");
	return 0;
}
双向带头循环链表_第1张图片

你可能感兴趣的:(算法)