加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

【数据结构】循环链表解决约瑟夫环问题

发布时间:2020-12-15 06:07:42 所属栏目:安全 来源:网络整理
导读:约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。 // 13_3.cpp : De

约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。

// 13_3.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <conio.h>
#include <string.h>
#include <stdio.h>
using namespace std;

typedef struct LNode
{
	int data;
	struct LNode *link;
}LNode,*Linklist;

void JOSEPHUS(int n,int k,int m)
{
	//create the cycle link list
	Linklist p,l,curr,r;
	p = (Linklist)malloc(sizeof(LNode));
	p->data = 0;
	p->link = p;
	curr = p;
	for (int i = 0; i < n; i++)
	{
		l = (Linklist)malloc(sizeof(LNode));
		l->data = i;
		l->link = curr->link;
		curr->link = l;
		curr = l;
	}
	//p->link = curr;

	//find the first occurrence of k
	r = p;
	while (k--)
	{
		r = p;
		p = p->link;
	}
	while (n--)
	{
		for (int s = m - 1; s >= 0; s--)
		{
			r = p;
			p = p->link;
		}
		r->link = p->link;
		cout << "The deleted value is: " << p->data << endl;
		free(p);
		//prepare for next time while loop
		p = r;
	}
}

int _tmain()
{
	JOSEPHUS(13,4,1);
	return 0;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读