约瑟夫环,循环链表实现

约瑟夫环的定义就不再赘述,直接上代码。
如果朋友能看完这个代码,相信你能理解接下面这个小故事。

有个人想从这个世界上消失,但是他又不想死,他想到了一个办法,他可以把另外一个人杀了,然后再用这个人的身份生活下去。(这个小故事与约瑟夫环无关)

#include <stdio.h>
#include <malloc.h>
struct node
{
    int data;
    struct node *next;
};

int main()
{
    int n, m;
    int i;
    int answer[100];
    int count = 0;
    struct node *head, *tail, *p;
    head = (struct node *)malloc(sizeof(struct node));
    head->data = -1;
    head->next = NULL;

    scanf("%d%d", &n, &m);
    if (n == 0 || m == 0)
    {
        free(head);
    }
    else
    {
        tail = head;
        for (i = 0; i < n; i++)
        {
            p = (struct node *)malloc(sizeof(struct node));
            p->data = i + 1;
            tail->next = p;
            tail = p;
        }
        p->next = head->next;
        i = 1;
        node *cru = head->next;
        node *nextnode;
        while (1)
        {
            if (i == m)
            {
                answer[count] = cru->data;
                count++;
                nextnode = cru->next;
                cru->data = nextnode->data;
                cru->next = nextnode->next;
                free(nextnode);
                i = 1;
            }
            cru = cru->next;
            i++;
            if (count == n - 1)
            {
                break;
            }
        }
    }

    for (i = 0; i < count; i++)
    {
        printf("%d\t", answer[i]);
    }
    free(head);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值