2013-06-02 2 views
0

을 통해 루프 반복은 :링크 목록 문제는 요세푸스 문제에 익숙하지 않은 경우 잘못된 노드

는 circle.They 서 N 군인이 모두 1로 시작하고 M.In 말에 의해서만 이동 실행 얻을 그들 중 하나가 살아있다. 아래 코드는 N과 M을 요구하고 마지막으로 서있는 플레이어를 생성했습니다. 프로그램이 상기 (2 생성 일어나는 웰은 1이므로 대신 1,8,15에서 M의 카운트를하지 개시 출력 (13) 되어야 M = 7;?

#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라고하자. ..... it elimintates 7,14 ......) 이것은 내가 당신의 도움이 필요한 곳입니다. (연결된 목록은 여전히 ​​어려운 개념입니다.) 이 수정 방법은 무엇입니까?

+1

최근 요세푸스를 다른 질문으로 보지 못했습니까? 그리고'# include' 지시어는 어디에 있습니까? 이것은 요구하기 전에 당신이 뭔가 정상적으로 변해야하는 코드입니다. – Jens

+0

@Jens 항상 1부터 시작해야합니까? –

+0

예 @pivovarit는 항상 1부터 시작합니다 –

답변

0

노드 제거 라인을 다른 위치에 두었습니다. 항상 노드 제 (M + 1)의 제거로 시작 있도록

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

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

당신은 후 처음부터 M 노드를 계산 루프를이 줄 을 두었다. 전에 이동해야 첫 번째 노드에서 시작됩니다.

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

} 

이게 뭡니까?

+0

와우 감사합니다. –

+0

@RediRedi 당신은 이미 매우 가까이있었습니다.) 대답을 수락함으로써 저에게 고맙다 수 있습니다. 건배! –

+0

시간이 있다면 [this] (http://stackoverflow.com/questions/16875295/anyone-familiar-with-josephus-prablemlinked-lists-in-c?noredirect=1#comment24364503_16875295) –