HYIT邱老师数据结构课程————环形链表

#include<iostream>
using namespace std;
struct Node {
	int number, data;
	Node *next;
};
Node *Tail(int n)//尾插法,有n个人
{
	if (n == 0)
		return NULL;
	int num;
	cin >> num;//每个人身上的数字
	Node *L = new Node;//定义一个类似于头节点的节点目的是环形有一个插入的起点
	L->data = num;
	L->number = 1;
	L->next = L;
	for (int i = 2; i < n; i++)
	{
		Node *p = new Node;
		int num;
		cin >> num;
		p->data = num;
		p->number = i;//确定是第几个孩子的数字
		p->next = L->next;
		L->next = p;
		L = L->next;
	}
	cout << endl;
	L = L->next;
	return L;
}
int Size(Node *&L)//链表结点个数
{
	if (L == NULL)
	{
		return 0;
	}
	int i = 1;//计数器
	Node *p = L->next;
	while (p != L)
	{
		i++;
		p = p->next;
	}
	return i;
}
int Visit(Node *&L)//遍历
{
	Node *p = L;
	if (p == NULL)
	{
		cout << "人数为0" << endl;
		return 0;	
	}
	cout << endl;
	cout << p->data << " ";
	p = p->next;
	while (p != L)
	{
		cout << p->data << " ";
		p = p->next;
	}
	cout << endl;
	return 1;
}
int Joseph(Node *&L, int m)//实现环形
{
	if (L == NULL)
	{
		cout << "人数为空,出列结束" << endl;
		return 0;
	}
	Node *p = L;
	while (p->next != L)
		p = p->next;
	cout << "出列编号为";
	for (int n = Size(L); n > 0; n--)
	{
		for (int i = 1; i <= m % n - 1; i = i + 5)
			p = p->next;
		cout << p->next->number << " ";
		m = p->next->data;
		Node *q = p->next;
		p->next = q->next;
		free(q);
	}
	return 1;
}
int main()
{
	int m, n;
	cout << "请输入初始编码(正整数)和人数" << endl;
	cin >> m >> n;
	cout << endl << "请输入" << n << "个人的编码" << endl;
	Node *L = Tail(n);
	cout << n << "个人的编码为";
	Visit(L);
	cout << n << "个人的出列顺序为" << endl;
	Joseph(L, m);
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值