【代码分享】

双向带头循环链表

头文件
#define _CRT_SECURE_NO_WARNINGS

#include
#include
#include
#include

typedef int LTDataType;
typedef struct ListNode
{
LTDataType data;
struct ListNode* prev;
struct ListNode* next;
}LTNode;

LTNode* LTInit();
void LTDestroy(LTNode* phead);
void LTPrint(LTNode* phead);
bool LTEmpty(LTNode* phead);

void LTPushBack(LTNode* phead, LTDataType x);
void LTPopBack(LTNode* phead);

void LTPushFront(LTNode* phead, LTDataType x);
void LTPopFront(LTNode* phead);
//在pos位置之后插入数据
void LTInsert(LTNode* phead,LTNode* pos, LTDataType x);
void LTErase(LTNode* phead,LTNode* pos);
LTNode* LTFind(LTNode* phead, LTDataType x);

源文件

#define _CRT_SECURE_NO_WARNINGS

#include"ListNode.h"

LTNode* LTInit()
{
	LTNode*phead = (LTNode*)malloc(sizeof(LTNode));
	if (phead == NULL)
	{
		printf("malloc失败!");
		exit(-1);
	}
	phead->next = phead;
	phead->prev = phead;
	phead->data = 0;

	return phead;
}
void LTDestroy(LTNode* phead)
{
	;
}
void LTPrint(LTNode* phead)
{
	LTNode* cur = phead->next;
	while (cur!=phead)
	{
		printf("%d ", cur->data);
		cur = cur->next;
	}
}

//尾插
void LTPushBack(LTNode* phead, LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("malloc失败!");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = phead;
	newnode->prev = phead->prev;

	phead->prev->next = newnode;
	phead->prev = newnode;
}
//尾删
void LTPopBack(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* tail = phead->prev;
	tail->prev->next = phead;
	phead->prev = tail->prev;
	free(tail);
}
//头插
void LTPushFront(LTNode* phead, LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("malloc失败!");
		exit(-1);
	}
	LTNode* head = phead->next;
	newnode->data = x;
	newnode->next = head;
	newnode->prev = phead;

	phead->next = newnode;
	head->prev = newnode;
}
//头删
void LTPopFront(LTNode* phead)
{
	assert(phead->next != phead);
	LTNode* tmp = phead->next->next;
	phead->next = tmp;
	free(tmp->prev);
	tmp->prev = phead;
}
//在pos位置之后插入数据
void LTInsert(LTNode* phead,LTNode* pos, LTDataType x)
{
	LTNode* newnode = (LTNode*)malloc(sizeof(LTNode));
	if (newnode == NULL)
	{
		printf("malloc失败!");
		exit(-1);
	}
	LTNode* tmp = pos->next;
	newnode->data = x;
	newnode->next = tmp;
	newnode->prev = pos;
	
	pos->next = newnode;
	tmp->prev = newnode;
}
void LTErase(LTNode* phead,LTNode* pos)
{
	assert(phead->next != phead);
	pos->prev->next = pos->next;
	pos->next->prev = pos->prev;
	free(pos);
}
bool LTEmpty(LTNode* phead)
{
	;
}
LTNode* LTFind(LTNode* phead, LTDataType x)
{
	LTNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

你可能感兴趣的:(c语言)