1. 程式人生 > >約瑟夫環問題迴圈連結串列實現

約瑟夫環問題迴圈連結串列實現

//n個人圍圈報數,報m出列,模擬出列的過程
#include <cstdio>
#include <cstdlib>

typedef struct node
{
	int data;
	struct node *next;
}node;

node *create(int n)
{
	node *p = NULL, *head;
	head = (node*)malloc(sizeof (node ));
	p = head;
	node *s;
	int i = 1;

	if( 0 != n )
	{
		while( i <= n )
		{
			s = (node *)malloc(sizeof (node));
			s->data = i++;    // 為迴圈連結串列初始化,第一個結點為1,第二個結點為2。
			p->next = s;
			p = s;
		}
		s->next = head->next;
	}

	free(head);

	return s->next ;
}

int main()
{
	int n=41;
	int m=3;
	int i;

	node *p = create(n);
	node *temp;

	m %= n;   

	while (p != p->next )
	{
		for (i = 1; i < m-1; i++)
		{
			p = p->next ;
		}

		printf("%d->", p->next->data );

		temp = p->next ;    //刪除第m個節點
		p->next = temp->next ;
		free(temp);

		p = p->next ;
	}

	printf("%d\n", p->data );

	return 0;
}