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;
    }

}

 

你可能感兴趣的:(java,数m,n个小孩)