溫馨提示×

如何使用c語言實(shí)現(xiàn)約瑟夫問題

小億
119
2024-03-19 16:44:42
欄目: 編程語言

約瑟夫問題是一個經(jīng)典的數(shù)學(xué)問題,可以使用C語言來實(shí)現(xiàn)。下面是一個簡單的C語言實(shí)現(xiàn)約瑟夫問題的示例代碼:

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

// 定義循環(huán)鏈表的節(jié)點(diǎn)結(jié)構(gòu)體
typedef struct Node {
    int data;
    struct Node* next;
} Node;

// 創(chuàng)建循環(huán)鏈表
Node* createCircularLinkedList(int n) {
    Node* head = NULL;
    Node* prev = NULL;
    
    for (int i = 1; i <= n; i++) {
        Node* newNode = (Node*)malloc(sizeof(Node));
        newNode->data = i;
        newNode->next = NULL;
        
        if (head == NULL) {
            head = newNode;
        } else {
            prev->next = newNode;
        }
        
        prev = newNode;
    }
    
    prev->next = head; // 將最后一個節(jié)點(diǎn)的next指向頭節(jié)點(diǎn),形成循環(huán)
    
    return head;
}

// 解決約瑟夫問題
int josephus(int n, int k) {
    Node* head = createCircularLinkedList(n);
    Node* current = head;
    Node* prev = NULL;
    
    // 找到要刪除的節(jié)點(diǎn)的前一個節(jié)點(diǎn)
    while (current->next != current) {
        for (int i = 1; i < k; i++) {
            prev = current;
            current = current->next;
        }
        
        Node* temp = current;
        prev->next = current->next;
        current = current->next;
        free(temp);
    }
    
    int result = current->data;
    free(current);
    
    return result;
}

int main() {
    int n = 5; // 總共有5個人
    int k = 2; // 每次報數(shù)為2
    
    int survivor = josephus(n, k);
    
    printf("Survivor: %d\n", survivor);
    
    return 0;
}

在上面的代碼中,首先定義了一個循環(huán)鏈表的節(jié)點(diǎn)結(jié)構(gòu)體,然后實(shí)現(xiàn)了創(chuàng)建循環(huán)鏈表和解決約瑟夫問題的函數(shù)。在main函數(shù)中,可以指定總共的人數(shù)n和每次報數(shù)的數(shù)字k,然后調(diào)用josephus函數(shù)來計算最后幸存者的編號。最后打印出最后幸存者的編號即可。

0