您的位置:首页 > 其它

链表经典问题:约瑟夫环的实现

2012-09-09 02:01 701 查看
对于约瑟夫环这个经典的链表问题,相信大家都不会陌生。

经常会以这种形式出现:

有13人围成一圈,从第一个人开始顺序报数,凡报到3的人退出圈子,编程找出最后留在圈子里的人原来的序号。

具体实现的代码如下:

#include <stdio.h>
#include <stdlib.h>

#define LEN 13
#define NUM 3

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

int main()
{
int i;
int length;
node *p;
node *ptr;
node *first;

first = (node *)malloc(sizeof(node));
if (first == NULL) {
printf("malloc fail!\n");
return -1;
}
first->num = 1;
p = first;

for(i = 1; i < LEN; i ++) {
p->next = (node *)malloc(sizeof(node));
p = p->next;
p->num = i+1;
}
p->next = first;
p = p->next;

length = LEN;
p = first;
while (length > 1) {
if (NUM == 1) {
for (i = 0; i < LEN - 1; i ++) {
ptr = p;
p = p->next;
free(ptr);
}
printf("the last one left is %d\n", p->num);
free(p);
return 0;
} else {
for (i = 0; i < NUM - 2; i++) {
p = p->next;
}
ptr = p->next;
p->next = ptr->next;
p = p->next;
free(ptr);
length --;
}
}
printf("the last one is %d\n", p->num);
free(p);

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: