java实现n个小孩围圈数m退1问题(单链)

转载请注明出处:http://shuiguaiqq.iteye.com/blog/2065943

n个人围一圈报数,数到m的人退出,直到最后只剩一个人。

问题也就不详细描述了,百度一搜一大堆,以前看过马士兵的视频,里面讲到过用的好像类似双链,有left和right的,我自己也实现过,但是搞来搞去容易让看代码的看晕,数组实现也搞过,感觉也不够直观,我比较喜欢结构逻辑清晰的代码,所以感觉还是单链清爽点,代码如下:

/**
 * n个人围一圈报数,数到m的人退出,直到最后只剩一个人
 */
public class CountQuit {
    static final int N = 500;
    static final int M = 3;
    static int remainPeople;
    static Node root = null;
    static {
        createCircle();
    }

    public static void main(String[] args) {
        startGrame();
    }

    public static void startGrame() {
        Node start = root;
        int count = 1;
        while (remainPeople > 1) {
            if (count == CountQuit.M - 1) {
                count = 0;
                start.setNext(start.getNext().getNext());
                remainPeople--;
            }
            start = start.getNext();
            count++;
        }
        System.out.println("最后剩下的小孩编号为:"+start.getCode());
    }

    public static void createCircle() {
        Node temp = null;
        for (int i = 0; i < CountQuit.N; i++) {
            if (i == 0) {
                root = new Node(i + 1);
                temp = root;
            } else {
                temp.setNext(new Node(i + 1));
                temp = temp.getNext();
                if (i == CountQuit.N - 1) {
                    temp.setNext(root);
                }
            }
        }
        remainPeople = CountQuit.N;
    }

}

class Node {
    private int code;
    Node next;

    public Node(int code) {
        this.code = code;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Node getNext() {
        return next;
    }

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

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值