约瑟夫问题(一)构建、遍历链表

约瑟夫问题是个有名的问题:N个人围成一圈,从第m个开始报数,第k个将出队,最后剩下一个,其余人都将出队。

1.构建一个单向循环的链表

2.遍历环形数组


public class Yuesefu {
    public static void main(String args[]) {
        Circle c=new Circle();
        c.add(6);
        c.show();
        
    }
}

class Circle{
    private Boy first=new Boy(0);
    public void add(int nums) {
        if(nums<1) {
            System.out.println("重输");
        }
        Boy curBoy=null;               //定义指针,辅助构建环形链表
        for(int i=1;i<=nums;i++) {
        Boy boy=new Boy(i);
            if(i==1) {                         //第一个小孩,自己形成环
                first=boy;
                boy.setNext(first);
                curBoy=boy;
            }
            else {
                curBoy.setNext(boy);
                boy.setNext(first);
                curBoy=boy;
            }
            
            
        }
        
    }
    public void show() {
        if(first==null) {
            return ;
        }
        Boy curBoy=first;
        while(curBoy!=null) {
            System.out.printf("%d号小孩\n",curBoy.getNo());
            if(curBoy.getNext()==first) {       //循环一圈后,跳出
                break;
            }else {
            curBoy=curBoy.getNext();
        }
        }
        
        
    }
    
    
    
}

class Boy{
    int no;
    Boy next;
    
    public Boy(int no) {
        this.no=no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

    public Boy getNext() {
        return next;
    }

    public void setNext(Boy next) {
        this.next = next;
    }
    
}

结果:

1号小孩
2号小孩
3号小孩
4号小孩
5号小孩
6号小孩

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值