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

约瑟夫环是一个数学的应用问题:已知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;
}

相关文章

【啊哈!算法】算法3:最常用的排序——快速排序       ...
匿名组 这里可能用到几个不同的分组构造。通过括号内围绕的正...
选择排序:从数组的起始位置处开始,把第一个元素与数组中其...
public struct Pqitem { public int priority; ...
在编写正则表达式的时候,经常会向要向正则表达式添加数量型...
来自:http://blog.csdn.net/morewindows/article/details/6...