//約瑟夫問題,n個人圍圈報數,報m的出列,最後剩下的是幾號?
#include <stdio.h>
#include <stdlib.h>
//結構體表示鏈表的結點
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++; //
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;
printf("出隊列的順序是:\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("\n\n最後留下來的人的號碼是:%d\n", p->data );
return 0;
}
[數據結構]約瑟夫問題
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.