zoukankan      html  css  js  c++  java
  • 使用链表实现Josephus环问题

    分析:先创建一个有total个结点的链表,然后头尾相连,构成一个环形链表。从第一个结点开始数到第m个结点,从链表中删除对应结点,表示小孩出圈。然后再从被删除结点的下一个结点重新开始计数,直到链表中剩下最后一个结点。

    #include <stdlib.h>
    #include 
    <stdio.h>
    #define LEN sizeof(struct child)
    struct child 
    {
        
    int num;
        
    struct child *next;
    };

    void main()
    {
        
    struct child *create(int num);
        
    int count(struct child *head,int total,int m);
        
    struct child *head;
        
    int total,m,n;
        printf(
    "please input total and start:");
        
    do 
        {
            scanf(
    "%d%d",&total,&m);
        } 
    while(total<2||m<2||m>total);
        head
    =create(total);
        n
    =count(head,total,m);
        printf(
    "\nThe left child is %d\n",n);
    }

    struct child *create(int num)
    {
        
    struct child *p1,*p2,*head;
        
    int i;
        p1
    =(struct child *)malloc(LEN);
        p1
    ->num=1;
        head
    =p1;
        
    for (i=2;i<=num;i++)
        {
            p2
    =(struct child *)malloc(LEN);
            p2
    ->num=i;
            p1
    ->next=p2;
            p1
    =p2;
        }
        p1
    ->next=head;                    //头尾相连
        return head;
    }

    int count(struct child *head,int total,int m)
    {
        
    struct child *p=head,*old;
        
    int i,j;
        
    for (i=1;i<total;i++)            //循环次数
        {
            
    for (j=1;j<m;j++)            //循环个数
            {
                old
    =p;
                p
    =p->next;
            }
            printf(
    "%3d",p->num);
            old
    ->next=p->next;
            free(p);
            p
    =old->next;
        }
        
    return p->num;
    }
  • 相关阅读:
    MySql(六)单表查询
    MySql(五)
    MySql(四)
    MySql(三)
    MySql(二)
    2016高管必看的五大互联网营销方法
    昨日股市暴跌熔断 赵薇亏3.3亿赔惨了(如何预测今年股市走向)
    何炅加入阿里音乐预示“互联网+”三大发展走向
    《老炮儿》的江湖道义就是互联网创业的规矩?
    世界互联网大会三大看点 传递什么信号?
  • 原文地址:https://www.cnblogs.com/qixin622/p/1238204.html
Copyright © 2011-2022 走看看