1. 程式人生 > >演算法-迴圈連結串列[約瑟夫問題之進階]

演算法-迴圈連結串列[約瑟夫問題之進階]

1.問題描述:
約瑟夫問題:進階
有 n 個人,初始時按照順序圍成一圈而坐,每個人都有一個密碼。
從任意一個人開始,制定報數上線M,當有人報數為M時,該人死亡,從下一個人開始報數,該人報數前指定報數上限M為該人的密碼。
至到所有人都死亡結束遊戲,輸出死亡順序編號。

2.程式碼:

#include "stdafx.h"
#include "stdlib.h"

using namespace std;

typedef int TYPE;

typedef struct Node {
    TYPE data;
    TYPE password;
    Node
* next; }Node; // random TYPE random[21] = { 0,5,4,5,6,3,10,19,4,7,12,14,15,17,21,5,22,23,24,25,26 }; Node* create_list(int n) { int i; Node* head = (Node*) malloc(sizeof(Node)); head->data = 1; head->password = random[1]; Node* temp = head; for (i = 2; i <= n;i++) { Node
* node = (Node*)malloc(sizeof(Node)); node->data = i; node->password = random[i%20 + 1]; if (i == n) { node->next = head; } temp->next = node; temp = node; } return head; } void joseph_new(int M,Node* head) { if (head == head->next) { printf("%d \n"
, head->data); return; } Node* current = head; Node* temp = head; while (M-- > 1) { temp = current; current = current->next; } temp->next = current->next; printf("%d \n", current->data); joseph_new(current->password, current->next); } int main() { Node* head = create_list(10); joseph_new(5,head); return 0; }