单向循环链表 约瑟夫

本文详细介绍了如何使用C语言创建循环链表,并实现约瑟夫环问题,即在给定的人群中按特定步长删除节点,直到剩下最后一位赢家。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <stdio.h>
#include <stdlib.h>
 
typedef struct Node {
    int value;
    struct Node *next;
} Node;
 
// 创建循环链表
Node* createCircularList(int n) {
    Node *head, *tail;
    for (int i = 1; i <= n; i++) {
        Node *newNode = (Node*)malloc(sizeof(Node));
        newNode->value = i;
        if (i == 1) {
            head = tail = newNode;
            tail->next = head; // 构成循环
        } else {
            tail->next = newNode;
            newNode->next = head;
            tail = newNode;
        }
    }
    return head;
}
 
// 打印循环链表
void printCircularList(Node *head) {
    Node *current = head;
    do {
        printf("%d ", current->value);
        current = current->next;
    } while (current != head);
    printf("\n");
}
 
// 执行约瑟夫环
Node* josephus(Node *head, int m) {
    Node *current = head;
    while (current->next != current) {
        for (int i = 1; i < m; i++) {
            current = current->next;
        }
        Node *toKill = current->next;
        printf("Eliminado: %d\n", toKill->value);
        current->next = toKill->next;
        free(toKill);
        current = current->next;
    }
    printf("Ganador: %d\n", current->value);
    return current;
}
 
int main() {
    int n = 5; // 例如,5个人
    int m = 2; // 例如,数数为2
    Node *head = createCircularList(n);
    printf("Inicial: ");
    printCircularList(head);
    Node *winner = josephus(head, m);
    printf("Final: ");
    printCircularList(winner);
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值