单链表实现约瑟夫环(JosephCircle)

本文介绍了一个使用链表实现约瑟夫环问题的C语言程序。首先定义了链表节点结构,并实现了创建节点、尾插法插入节点及约瑟夫环算法。通过示例展示了如何使用这些函数来解决约瑟夫环问题。

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

#include <stdio.h>
#include <assert.h>
#include <malloc.h>
typedef int DataType;

typedef struct ListNode
{
    DataType data;
    struct ListNode *next;
}ListNode;

static ListNode *CreateNode(DataType data)
{
    ListNode *newNode = (ListNode *)malloc(sizeof(ListNode));
    assert(newNode);
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
/*  尾插  */
void ListPushBack(ListNode ** ppFirst, DataType data)
{
    ListNode *newNode = CreateNode(data);
    if (*ppFirst == NULL)
    {
        *ppFirst = newNode;
        return;
    }
    ListNode *cur = *ppFirst;
    while (cur->next != NULL)
    {
        cur = cur->next;
    }
    cur->next = newNode;
}

/*  约瑟夫环  */
ListNode * JosephCycle(ListNode *first, int k)
{
    // 第一步,链表构成环
    ListNode *tail = first;
    while (tail->next != NULL) {
        tail = tail->next;
    }
    tail->next = first;

    // 第二步
    ListNode *cur = first;
    // 结束条件是链表中只剩一个结点
    while (cur->next != cur) {
        ListNode *prev = NULL;
        for (int i = 0; i < k - 1; i++) {
            prev = cur;
            cur = cur->next;
        }

        // cur 就是我们要删除的结点
        prev->next = cur->next;
        free(cur);

        // 让循环继续
        cur = prev->next;
    }

    cur->next = NULL;
    return cur;
}

void TestJosephCycle()
{
    ListNode *first = NULL;
    for (int i = 1; i <= 5; i++) {
        ListPushBack(&first, i);
    }

    ListNode *sur = JosephCycle(first, 4);
    printf("%d\n", sur->data);
}
int main()
{
    TestJosephCycle();
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值