约瑟夫问题(链表)

#include<iostream>
using namespace std;
struct Node {

	int num;
	Node *ahead;
	Node *next;
};
Node *Create(int N) {//创建N个节点的循环链表
	int n = 1;
	Node *node = new Node;
	node-> num = n;
	Node *head = node;//指向第一个节点
	Node *tail = head;//指向最后一个节点
	while (n++ < N) {
		node = new Node;//建立新节点
		node->num = n;//赋值
		tail->next = node;//接入新节点
		node->ahead = tail;
		tail = tail->next;//尾巴后移
	}
	tail->next = head;//首尾相接
	head->ahead = tail;
	return head;

}
Node *Search(Node *head, int P) {//找第P个节点
	while (head->num != P) {
		head = head->next;

	}
	return head;
}
Node *Release(Node *head, int M) {//释放从head开始的第M个节点
	int count = 1;
	Node *temp = head;
	while (count < M) {//寻找第M个节点
		temp = temp->next;
		count++;
	}
	temp->ahead->next = temp->next;//移除它
	temp->next->ahead = temp->ahead;
	cout << temp->num << ",";
	head = temp->next;
	delete temp;//释放其内存空间
	return head;
}
int main() {
	int N, P, M = 0;//N-起始节点数,P-开始节点
	cin >> N >> P >> M;//每次释放第M个节点
	Node *head = Create(N);//创建N个节点的环
	head = Search(head, P);//找到第P个节点
	while (head->next != head) {//不断释放第M个元素,直到最后只剩一个
		head = Release(head, M);
	}
	cout << head->num;
	system("pause");
	return 0;



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值