【转】约瑟夫环算法---------题目:有n个人围成一圈,顺序排号,从第一个开始报数(从1到3报数),凡报到3的人退出圈子,问最后最后留下的是原来第几号的那位....

提示:用环形链表实现

对于这个题目其实就是用c语言的循环链表实现一个约瑟夫环。我们可以定义一个循环链表,将这n个人加入到链表中,然后定义三个节点指针在链表上循环,移动跨度为3,利用链表的循环功能每次删除第三个节点,这边要注意的一个问题就是你定义的是3个指针,且在循环中他们彼此也都是有

->next关系,一般我们判断循环结束条件时都是一个节点的下一个节点是否为它本身(如ptr->next == ptr),这里我们要注意循环体中链接方向否则很可能出现无用指针导致错误,因为最后我们要剩下一个节点那么ptr->next为NULL,而剩下的不能是NULL->next.

具体程序,如下:

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

struct node
{
    int num;
    struct node *next;
};

struct node *head;
struct node *last;

void cre_list()
{
    head = (struct node *)malloc(sizeof(struct node));
    last = head;
    head->next = head;
}

 

void display_node()
{
    struct node *ptr = head->next;
    while(ptr != head)
    {
        printf("%d\t",ptr->num);
        ptr = ptr->next;
    }
    printf("\n");
}

void add_node(int num)
{
    struct node *ptr = (struct node *)malloc(sizeof(struct node));
    ptr->num = num;
    ptr->next = head;
    last->next = ptr;
    last = ptr;
}

void rev_node()
{
    struct node *ptr = head;
    last->next = head->next;
    head = head->next;
    free(ptr);
}

void tiren_node()
{
    struct node *ptr = head;
    struct node *str = ptr->next;
    struct node *qtr = str->next;
    while(ptr->next != ptr)
    {
        str = ptr->next;
        qtr = str->next;
        str->next = qtr->next;
        ptr = str->next;
    }
    printf("%d\n",ptr->num);
}

int main()
{
    int i = 0;
    cre_list();
    int n;
    printf("please input n:\n");
    scanf("%d",&n);
    printf("%d\n",n);
    for(i = 1;i <= n;i++)
    {
        add_node(i);
    }
    display_node();
    rev_node();
    tiren_node();
    return 0;
}

转载于:https://www.cnblogs.com/yihujiu/p/6627822.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值