@quinn
2015-03-20T09:27:10.000000Z
字数 666
阅读 1701
数据结构
从N个人中选出一个领导人,方法如下:
所有人排成一个圆圈,按顺序每隔第M个人淘汰出局,然后剩下的人聚拢重新形成圆圈,找出最后剩下的那个人
参考:《算法:C语言实现》 P52
#include <stdio.h>
#include <stdlib.h>
typedef int elem_type;
typedef struct Node node;
struct Node
{
elem_type elem;
node* next;
};
int main(int argc, char *argv[])
{
int N = atoi(argv[1]);
int M = atoi(argv[2]);
node* h = (node*) malloc(sizeof(h)); //head
node *x = h;
h->elem = 1;
h->next = h;
for (int i = 2; i <= N; i++)
{
x->next = (node*) malloc(sizeof(x));
x = x->next;
x->elem = i;
x->next = h; //指向head,循环
}
//x为最末一位
while (x != x->next )
{
for (int i = 1; i < M; i++)
{
x = x->next; //当i=1, x->elem=1;
//当i=M-1, x->elem = M-1; 当 i = M, x为第M-1个
}
printf("Delete: %d\n", x->next->elem);
x->next = x->next->next;
}
printf("The leader's NO. is %d\n", x->elem);
system("pause");
}