Josephus问题

Posted ssdut_yrp

tags:

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

public class Link 
    public long lData;
    public Link next;

    public Link(long lData)
        this.lData=lData;
    

    public void displayLink()
        System.out.print(lData+" ");
    

public class CircleList 
    private Link current;
    private int nItems;

    public CircleList()
        current=null;
    

    public void insert(long value)
        Link newLink = new Link(value);
        if(current==null)
            current=newLink;
            newLink.next=newLink;
        else
            newLink.next=current.next;
            current.next=newLink;
            current=newLink;//插入元素,current要移动要新元素
        
        nItems++;
    

    public long remove()
        long temp = current.next.lData;
        if(current.next==current)
            current=null;
        else
            current.next=current.next.next;
        
        nItems--;
        return temp;
    

    public long peek()
        return current.next.lData;
    

    public Link find(long value)
        Link temp =current;
        Link result=null;
        if(current==null)
            return result;
        
        do
            step();//从current的下一个元素开始
            if(current.lData==value)
                result=current;
                current=temp;//还原current到原来的位置,这样就不会打乱插入的顺序,current指向最后插入的元素
            
        while(current!=temp);//current到原来的位置,一周循环结束
        return result;
    

    public void step()
        if(current!=null)
            current=current.next;// 调用step()方法后,顺序会被打乱
        
    

    public void display()
        if(current!=null)
            Link temp =current;
            do
                step();// 从current的一下个开始显示
                System.out.print(current.lData + " ");
            while(current!=temp);
        
        System.out.println();
    

    public boolean isEmpty()
        return (current==null);
    

    public int size()
        return nItems;
    
public class Josephus 
    /**
     * @param args
     */
    public static long getJosephus(int number)
        CircleList theCircleList = new CircleList();
        for(int i=1;i<=number;i++)
            theCircleList.insert(i);
        
        System.out.print("原始圈子:");
        theCircleList.display();
        System.out.print("出圈顺序:");
        for(int i=1;i<number;i++)//要删掉number-1个人
            for(int j=1;j<4;j++)//不能数到4,remove删掉下一个
                theCircleList.step();
            
            System.out.print(theCircleList.remove()+" ");
        
        System.out.println();
        return theCircleList.peek();
    

    public static void main(String[] args) 
        // TODO Auto-generated method stub
        long number = Josephus.getJosephus(7);
        System.out.println("Josephus的编号是:"+number);
    

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

Josephus问题的不同实现方法与总结

线性表应用--Josephus问题的解法(Python 版)

Josephus问题

Josephus环问题

[PTA]约瑟夫环(Josephus)问题

约瑟夫问题(Josephus)