循环链表

循环链表是在单向链表的基础上,将尾节点指回头结点。

#include<iostream>
using namespace std;

typedef int ELemtype;

typedef struct CLNode {        //循环链表的节点
	ELemtype elem;
	struct CLNode *next;
}*CLList;

void init_List(CLList Head) {            //初始化链表,使的next指针指向本身
	Head->elem = NULL;
	Head->next = Head;
}

void Creat_List(CLList Head) {       //创建链表
	int elem = 1;
	CLList p = Head;
	while (elem) {
		cout << "Please enter the element you wanna insert(0 for end):";
		cin >> elem;
		if (elem) {
			CLList node;
			node = (CLNode *)malloc(sizeof(CLNode));
			if (p->elem == NULL) p->elem = elem;              //链表为空是进行
			else {
				CLList node;
				node = (CLNode *)malloc(sizeof(CLNode));
				node->elem = elem;
				p->next = node;
				node->next = Head;
				p = p->next;
			}
		}
	}
}

int GetLength(CLList L) {              //求链表长度
	int len=0;
	CLList p = L;
	if (p->elem == NULL)return 0;
	p = p->next;
	++len;
	while (p != L) {
		++len;
		p = p->next;
	}
	return len;
}

void insert_Node(CLList L, ELemtype elem, int pos) {         //在指定位置插入指定元素
	if (L->elem == NULL) { cout << "The list is empty!" << endl; return; }
	int len = GetLength(L);
	if (pos <= 0 || pos > len) { cout << "The position is wrong!" << endl; return; }
	CLList p=L;
	CLList node;
	node = (CLNode *)malloc(sizeof(CLNode));
	node->elem = elem;
	if (pos == 1) {
		for (int i = 1; i < len; ++i)p = p->next;
	}
	else {
		for (int i = 1; i < pos - 1; ++i)p = p->next;
	}
	node->next = p->next;
	p->next = node;
}

CLList delete_Node(CLList L, int pos) {        //删除指定位置上的元素
	if (L->elem == NULL) { cout << "The list is empty!" << endl; return L=NULL; }
	int len = GetLength(L);
	if (pos <= 0 || pos > len) { cout << "The position is wrong!" << endl; }
	CLList p = L;
	CLList temp;
	if (pos == 1) {
		p = p->next;
		while (p->next != L)p = p->next;
		temp = L;
		L = L->next;
		p->next = L;
	}
	else {
		for (int i = 1; i < pos - 1; ++i)p = p->next;
		temp = p->next;
		p->next = p->next->next;
	}
	delete temp;
	return L;
}

void output_List(CLList L) {                   //遍历链表
	CLList p = L;
	if (p->elem == NULL) { cout << "This is a empty list!" << endl; }
	else {
		cout << p->elem << " ";
		p = p->next;
		while (p != L) {
			cout << p->elem << " ";
			p = p->next;
		}
		cout << endl;
	}
}

void test() {
	CLList L;
	L = (CLNode *)malloc(sizeof(CLNode));
	init_List(L);
	Creat_List(L);
	output_List(L);
	cout << "len=" << GetLength(L) << endl;
	insert_Node(L, 36, 3);
	output_List(L);
	L=delete_Node(L, 1);
	output_List(L);
}

void main() {
	test();
	system("pause");
}
结果如图:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值