约瑟夫环的暴力解法

#include <iostream>
#include <list>
using namespace std;
struct Node
{
	Node* next;
	int val;
	int num;
};
int main(void)
{
	int N;
	cin>>N;
	int i;
	Node* head=new Node;
	Node* prev=head;
	for(i=1;i<N+1;i++)
	{
		int j;
		cin>>j;
		Node* node=new Node;
		node->num=i;
		node->val=j;
		prev->next=node;
		prev=node;
		if(i==N)
			node->next=head->next;
	}
	int m;
	cin>>m;
	Node* node=head->next;
	prev=head;
	for(i=1;i<N+1;i++)
	{
		if(i==N)
		{
			cout<<node->val;break;
		}
		int j;
		for(j=1;j<m;j++)
		{
			prev=node;
			node=node->next;
		}
		//del node
		//prev->next=node->next;
		m=node->num;
		cout<<node->val<<endl;
		prev->next=node->next;
		delete node;
		node=prev->next;
	}
	delete node;
	delete head;
	return 0;
}


posted on 2013-08-12 18:51  bbsno  阅读(264)  评论(0编辑  收藏  举报

导航