1. 约瑟夫问题

题目(要求用循环链表实现)

约瑟夫问题是一个经典的问题。已知n个人(不妨分别以编号1,2,3,...,n 代表 )围坐在一张圆桌周围,从编号为 k 的人开始,从1开始顺时针报数1, 2, 3, ...,顺时针数到m 的那个人,出列并输出。然后从出列的下一个人开始,从1开始继续顺时针报数,数到m的那个人,出列并输出,...依此重复下去,直到圆桌周围的人全部出列。

输入:n, k, m

输出:按照出列的顺序依次输出出列人的编号,编号中间相隔一个空格,每10个编号为一行。

非法输入的对应输出如下

a)

输入::n、k、m任一个小于1
输出:n,m,k must bigger than 0.

b)

输入:k>n

输出:k should not bigger than n.

例:

输入:9,3,2

输出:4 6 8 1 3 7 2 9 5


C++完整代码

cpp 复制代码
#include <iostream>
#include <string>
#include <vector>
using namespace std;

struct ListNode {
	int val;
	ListNode* next;
	ListNode(int x) : val(x), next(NULL) {}
};

int main() {
	int n, k, m;
	scanf("%d%*c%d%*c%d", &n, &k, &m);

	if (n < 1 || k < 1 || m < 1) {
		cout << "n,m,k must bigger than 0." << endl;
		return 0;
	}
	if (k > n) {
		cout << "k should not bigger than n." << endl;
		return 0;
	}

	// 创建循环链表
	ListNode* head = new ListNode(1);
	ListNode* cur = head;
	for (int i = 2; i <= n; i++) {
		cur->next = new ListNode(i);
		cur = cur->next;
	}
	cur->next = head;

	// 将cur指针移动到编号为k的节点
	for (int i = 0; i < k - 1; i++) {
		head = head->next;
	}
	int count = 0;
	// 开始报数并出列
	while (n) {
		if (m > 1) {// 数到m的前一个节点
			for (int i = 0; i < m - 2; i++) {
				head = head->next;
			}
			// 出列并记录编号
			ListNode* temp = head->next;
			cout<<temp->val;
			head->next = temp->next;
			head = head->next;
			delete temp;
			n--;
			count++;
		}
		else {
			cout<<head->val;
			head = head->next;
			n--;
		}
		if (n == 0 && count % 10 != 0) cout << endl;
		else if (count % 10 == 0) cout << endl;
		else cout << " ";
	}
	return 0;
}
相关推荐
星恒随风6 分钟前
从0实现C++ AI大模型接入SDK(三):环境搭建与ChatSDK快速上手——实现我们的第一个AI聊天程序
linux·开发语言·c++·人工智能·笔记
风落青芜8 分钟前
排序算法(二):选择排序、堆排序与冒泡排序
c语言·开发语言·数据结构·算法·排序算法
Navigator_Z38 分钟前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
h_a_o777oah1 小时前
【数据结构】FHQ Treap:无旋转的平衡 BST
数据结构·c++·算法·acm·平衡树·treap·fhq treap
fengkai45451 小时前
Python运维实战
运维·开发语言·python·ssh·sftp·paramiko
撸码猿1 小时前
Ladybird 进入 alpha:从零写的浏览器引擎现在能下载了
c++·rust·开源·浏览器·ladybird
草履虫AI课2 小时前
强化学习从零到一 07|重要性采样:借别人的数据,算自己的期望
算法·强化学习
AAA修煤气灶刘哥2 小时前
明明输入了完整报错,知识库怎么净给我相似答案?
人工智能·后端·算法
ShineWinsu3 小时前
对于Qt:重写事件步骤的解析
开发语言·c++·qt·客户端·事件·鼠标事件·步骤
2501_930707783 小时前
使用C#从 PowerPoint 演示文稿中提取图片
开发语言·c#·powerpoint