带头节点的循环链表

带头节点的循环链表,循环链表的尾节点指向头节点

带头节点的循环链表_第1张图片

头文件clist.h

#pragma once
//带头节点的循环链表
//循环链表的尾节点指向头节点

typedef struct CNode
{
	int data;//数据域
	struct CNode *next;//指向下一个节点的地址
}CNode,*CList;


void InitList(CList plist);

//头插
bool Insert_head(CList plist,int val);

//尾插
bool Insert_tail(CList plist,int val);

bool IsEmpty(CList plist);

bool Delete(CList plist,int key);

CNode * Search(CList plist,int key);//CList

void Show(CList plist);

void Destroy(CList plist);

void Clear(CList plist);

//获取有效数据的个数
int GetLength(CList plist);

//链表逆置
void Reverse(CList plist);

实现功能 clist.cpp 文件

#include 
#include 
#include 
#include "clist.h"

//头节点的next指向自己
void InitList(CList plist)
{
	assert(plist != NULL);
	if(plist == NULL)
	{
		return;
	}

	plist->next = plist;
}

//头插
bool Insert_head(CList plist,int val)
{
	CNode *p = (CNode *)malloc(sizeof(CNode));
	p->data = val;

	p->next = plist->next;
	plist->next = p;

	return true;
}

//尾插
bool Insert_tail(CList plist,int val)
{
	CNode *p;
	for(p=plist;p->next!=plist;p=p->next) ;

	CNode *q = (CNode *)malloc(sizeof(CNode));
	q->data = val;

	//将q插入在p的后面
	q->next = p->next;//q->next = plist;
	p->next = q;

	return true;
}

bool IsEmpty(CList plist)
{
	return plist->next == plist;
}

static CNode *SearchPri(CList plist,int key)
{
	for(CNode *p=plist;p->next!=plist;p=p->next)
	{
		if(p->next->data == key)
		{
			return p;
		}
	}
	return NULL;
}

bool Delete(CList plist,int key)
{
	CNode *p = SearchPri(plist,key);
	if(p == NULL)
	{
		return false;
	}

	CNode *q = p->next;
	p->next = q->next;	
	free(q);

	return true;
}

CNode * Search(CList plist,int key)//CList
{
	for(CNode *p=plist->next;p!=plist;p=p->next)
	{
		if(p->data == key)
		{
			return p;
		}
	}

	return NULL;
}

void Show(CList plist)
{
	for(CNode *p=plist->next;p!=plist;p=p->next)
	{
		printf("%d ",p->data);
	}
	printf("\n");
}

void Destroy(CList plist)
{
	CNode *p;
	while(plist->next != plist)
	{
		p = plist->next;
		plist->next = p->next;
		free(p);
	}
}

void Clear(CList plist)
{
	Destroy(plist);
}

//获取有效数据的个数
int GetLength(CList plist)
{
	int count = 0;

	for(CNode *p=plist->next;p!=plist;p=p->next)
	{
		count++;
	}

	return count;
}

//链表逆置
void Reverse(CList plist)
{
	CNode *p = plist->next;
	CNode *q ;
	plist->next = plist;//****

	while(p != plist)
	{
		q = p->next;
		//将p利用头插的方法插入到链表中
		p->next = plist->next;
		plist->next = p;
		p = q;
	}
}


测试test.cpp文件

int main()
{
	CNode n;
	InitList(&n);
	for(int i=0;i<=10;i++)
	{
		Insert_head(&n,i);
	}
	Show(&n);
	
	Delete(&n,10);
	Show(&n);
	Reverse(&n);
	Show(&n);
}


最终运行结果:

带头节点的循环链表_第2张图片



你可能感兴趣的:(c语言,数据结构)