Josephus约瑟夫环问题


/*********************************************************************
题目:有n个人围成一圈,顺序排号,从第一个开始报数
(从1到3报数),凡报到3的人退出圈子,问最后最后留下
的是原来第几号的那位.
提示:用循环链表完成
*********************************************************************/
#include<stdio.h>
#include<stdlib.h>
struct node
{
    int num;
    struct node *next;
};
struct node *head=NULL;
struct node *last=NULL;
cre_list()  //初始化结点
{
    head = (struct node *)malloc(sizeof(struct node));
    head->next = head;
last=head;
}
add_node(int num)  //插入结点
{
    struct node *ptr = (struct node *)malloc(sizeof(struct node));
if(head->num==0)
{
    head->num=num;
}
else
{
ptr->num = num;
ptr->next = head;
last->next = ptr;
last=ptr;
}
}
display_node()  //遍历链表
{
    struct node *p = head;
    do
    {
        printf("%d\t",p->num);
        p = p->next;
    }while(p != head);
    printf("\n");
}
delete_node(int num)   //删除
{
    struct node *p,*q;  
    p = last;
    q = head;
    int n=1;
while(q->next!=q )
{
    if(n == num)
    {
p->next=q->next;
free(q);
q=p->next;
        n=1;
continue;
    }
q=q->next;
p=p->next;
n++;
}
}
int main()
{
    int i=1;
    cre_list();
    for(i;i<7;i++)
    {
        add_node(i);
    }
display_node();
delete_node(3);
display_node();
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值