约瑟夫问题

Posted unclehu

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了约瑟夫问题相关的知识,希望对你有一定的参考价值。

package org.demo.linkedList;


/**
 * 
 * 问题可用单链表循环解决
 * 问题:N个人围成一圈,从第一个开始报数,第M个将被杀掉,最后剩下一个,其余人都将被杀掉
 *
 */
public class Josefu 

    public static void main(String[] args) 
        // TODO Auto-generated method stub
        Josefu jose = new Josefu();
        jose.solveJosefu(6, 1, 5);
    
    
    public void solveJosefu(int num/*人数*/,int beg/*开始位置*/,int count/*报数*/) 
        
        if(num<beg||num<1||beg<1||count<1) 
            System.out.println("输入参数出错");
            return;
        
        
        CircleSingleLinkedList boys = new CircleSingleLinkedList(num);
        Boy curBoy = boys.getFirst(); //当前小孩
        Boy preBoy = curBoy; //指向当前小孩的前一个位置
        //初始化curBoy和preBoy位置 beg
        for(int i = 1 ;i<beg;i++) 
            curBoy = curBoy.getNext();
        
        
        while(preBoy.getNext()!=curBoy) 
            preBoy = preBoy.getNext();
        
        //end
        
        //开始报数,这个循环相当找出出列的人,并且将它删除
        while(preBoy!=curBoy) 
            for(int i=0;i<count-1;i++) 
                curBoy = curBoy.getNext();
                preBoy = preBoy.getNext();
            
            System.out.printf("出列的boy:%d\n" , curBoy.getNum()); //要出列的人
            preBoy.setNext(curBoy.getNext());
            curBoy = curBoy.getNext();
        
        
        System.out.printf("最后留在队列的boy:%d\n",curBoy.getNum());
    



class CircleSingleLinkedList
    
    private Boy first = null;
    
    public CircleSingleLinkedList(int num) 
        createCircleList(num);
    
    
    public void createCircleList(int num) 
        if(num<1)
            return;
        
        first = new Boy(1);
        first.setNext(first);
        Boy curBoy = first;
        Boy temp = null;
        for(int i=2;i<=num;i++) 
            temp = new Boy(i);
            curBoy.setNext(temp);
            temp.setNext(first);
            curBoy = curBoy.getNext();
        
    

    public Boy getFirst() 
        return first;
    

    public void setFirst(Boy first) 
        this.first = first;
    
    
    


class Boy
    private int num;
    
    private Boy next;
    
    

    public Boy(int num) 
        super();
        this.num = num;
    

    public int getNum() 
        return num;
    

    public void setNum(int num) 
        this.num = num;
    

    public Boy getNext() 
        return next;
    

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

 

以上是关于约瑟夫问题的主要内容,如果未能解决你的问题,请参考以下文章

约瑟夫问题

约瑟夫环问题

用ArrayList(解决约瑟夫问题)

1139 约瑟夫环问题

Musical Chairs(约瑟夫环问题)

约瑟夫问题