链表问题 - 循环遍历错误的节点

时间:2013-06-02 19:51:17

标签: c loops data-structures linked-list josephus

如果你不熟悉约瑟夫斯问题:

有N名士兵站成一个圈子。他们全部从1开始执行并由M移动。最后,只有其中一人活着。 下面的代码询问N和M并生成最后一名球员。

#include <stdio.h>
#include <stdlib.h>
int main()
{
int N, M;
struct node { int player_id; struct node *next; }
struct node *p, *q;
int i, count;

printf("Enter N (number of players): "); scanf("%d", &N);
printf("Enter M (every M-th payer gets eliminated): "); scanf("%d", &M);

// Create circular linked list containing all the players:

p = q = malloc(sizeof(struct node));

p->player_id = 1;

for (i = 2; i <= N; ++i) {
    p->next = malloc(sizeof(struct node));
    p = p->next;
    p->player_id = i;
}  

p->next = q;// Close the circular linkedlist by having the last node point to the 1st  

// Eliminate every M-th player as long as more than one player remains:

for (count = N; count > 1; --count) {
   for (i = 0; i < M - 1; ++i)
      p = p->next;

   p->next = p->next->next;  // Remove the eiminated player from the circular linkedl
}

printf("Last player left standing is %d\n.", p->player_id);

return 0;
}

假设N = 17; M = 7,输出应为13 上面的程序生成2(会发生什么?好吧它从M开始计数而不是从1计数而不是1,8,15 ......它排除了7,14 ......) 这是我需要你的帮助(因为链接列表对我来说仍然是一个困难的概念)。 如何修改这个?

1 个答案:

答案 0 :(得分:0)

您已将节点删除行放在错误的位置。

for (count = N; count > 1; --count) {
   for (i = 0; i < M - 1; ++i)
      p = p->next;

   p->next = p->next->next;
}

您将此行放在循环之后,从一开始就对M个节点进行计数,因此它始终以删除第(M + 1)个节点开始。您应该在之前移动它,以便它从第一个节点开始。

for (count = N; count > 1; --count) {
   p->next = p->next->next;
            for (i = 0; i < M - 1; ++i) p = p->next;

}

这是你在找什么?