java练习7.17

package com.gzw;

public class LinkedList {
    
    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        CycLink cyclink = new CycLink();
        cyclink.setLength(8);//链表长度
        cyclink.createLink();//创建链表
        cyclink.setK(1);
        cyclink.setM(5);
        cyclink.run();
    }
}

class Child{
    int num; //编号
    Child nextChild = null;
    public Child(int num){
        this.num = num;
    }
}

//构造环形链表
class CycLink{
    Child firstChild = null; //    指向第一个小孩,不能动
    Child temp = null;
    int length = 0;//小孩总数
    int k = 0; //从第k个开始
    int m = 0; //数m个

    public void setM(int m){
        this.m = m;
    }    

    public void setLength(int length){
        this.length = length;
    }

    public void setK(int k){
        this.k = k;
    }

    public void run(){
        Child temp = this.firstChild;
        for(int i=1;i<k;i++){  //找到第k个人
            temp = temp.nextChild;            
        }
        while(this.length!=1){
            for(int j=1;j<m;j++){
                temp = temp.nextChild;
            }
            Child temp2 = temp;  //找到要出圈的前一个小孩
            while(temp2.nextChild!=temp){
                temp2 = temp2.nextChild;
            }
            System.out.println("出圈的小孩编号:" + temp2.nextChild.num);
            temp2.nextChild = temp.nextChild; //将第m个小孩退出圈
            temp = temp.nextChild;
            this.length--;
        }
        System.out.println("最后出圈的小孩:" + temp.num);
    }
    
    public void createLink(){
        for(int i=1;i<=length;i++){
            if(i==1){
                Child ch = new Child(i);
                this.firstChild = ch;
                this.temp = ch;
            }
            else if(i==length){
                Child ch = new Child(i);
                temp.nextChild = ch;
                temp = ch;
                temp.nextChild = this.firstChild;
            }
            else{
                Child ch = new Child(i);
                temp.nextChild = ch;
                temp = ch;
            }
        }
    }
}
java练习7.17