Java教程

线性表的链式存储结构——循环链表

本文主要是介绍线性表的链式存储结构——循环链表,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

线性表的链式存储结构——循环链表

目录
  • 线性表的链式存储结构——循环链表
  • 1 存储结构
  • 2操作循环链表
  • 3 创建循环链表
  • 4 打印循环链表

​ 循环链表就是单链表最后一个结点的指针不指向NULL,而是指向头结点。

1 存储结构

typedef int ElemType;
typedef int LIST_STATUS;

typedef struct _Node {
	ElemType Data;
	struct _Node *Next;
}Node;

2操作循环链表

​ 创建,打印,合并两个循环链表的操作

代码:

LIST_STATUS OperatorLoopLinkList(void) {
	Node *LoopHead;
	int CreateNum = 3;
	
	LIST_STATUS Status;

	/*Create empty link list*/
	LoopHead = (Node *)malloc(sizeof(Node));

	Status = CreateLoopLinkList(LoopHead, CreateNum);
	if (SUCCESS == Status) {
		printf("CreateLoopLinkList succeed!\n");
	} else {
		printf("CreateLoopLinkList failed!\n");
	}

	PrintLoopLinkList(LoopHead);
}

3 创建循环链表

​ 创建结点数为3的循环链表

代码:

LIST_STATUS CreateLoopLinkList(Node *LoopHead, int CreateNum) {
	int i = 0;
	Node *TraNode;
	Node *CreateNode;

	printf("CreateLoopLinkList start\n");

	if (NULL == LoopHead) {
		return ERROR;
	}

	/*Create TailNode*/
	LoopHead->Data = CreateNum;
	LoopHead->Next = NULL;

	TraNode= LoopHead;

	for (i = 1; i <= CreateNum; ++i) {
		CreateNode = (Node *)malloc(sizeof(Node));
		CreateNode->Data = i;
		
		/*Insert Node in the tail of link list*/
		CreateNode->Next = TraNode->Next;
		TraNode->Next = CreateNode;

		/*Move TraNode*/
		TraNode = TraNode->Next;
	}

	/*Deal with the last Node*/
	if (NULL == TraNode->Next) {
		TraNode->Next = LoopHead;
	}

	printf("CreateLoopLinkList end\n");
	return SUCCESS;
}

结果:

CreateLoopLinkList start

CreateLoopLinkList end

CreateLoopLinkList succeed!

PrintLoopLinkList start

TraNode->Data = 3

TraNode->Data = 1

TraNode->Data = 2

TraNode->Data = 3

PrintLoopLinkList end

4 打印循环链表

代码:

LIST_STATUS PrintLoopLinkList(Node *LoopHead) {
	Node *TraNode;

	printf("PrintLoopLinkList start\n");

	TraNode = LoopHead;

	if (NULL == LoopHead) {
		return ERROR;
	}

	while (TraNode->Next != LoopHead) {
		printf("TraNode->Data = %d\n", TraNode->Data);
		TraNode = TraNode->Next;
	}
	
	if (TraNode->Next == LoopHead) {
		printf("TraNode->Data = %d\n", TraNode->Data);	
	}

	printf("PrintLoopLinkList end\n");
}

这篇关于线性表的链式存储结构——循环链表的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!