首页 > 代码库 > 链表下的约瑟夫环

链表下的约瑟夫环

首先把上面的双向链表改为循环双向链表

public class MyLinkedList2<E> {

    /**
     * 第一个
     */
    transient MyNode first = null;
    /**
     * 最后一个
     */
    transient MyNode last = null;

    transient int size =0;

    Object[] obs = null;

    MyLinkedList2(Object[] obs){
        this.obs = obs;
        MyNode preNode = null;
        for (int i = 0; i < obs.length; i++) {
            MyNode succ = new MyNode(preNode,(E)(obs[i]),null);

            if(preNode!=null){
                preNode.next=succ;
            }else {
                first=succ;
            }
            preNode = succ;
            last=succ;
            size++;
        }

        last.next=first;
        first.pre=last;

    }

    class MyNode{
        E w;
        MyNode pre = null;
        MyNode next=null;

        public MyNode(MyNode pre,E w, MyNode next) {
            this.w = w;
            this.next = next;
            this.pre=pre;
        }
    }

    public int length(){
        return size;
    }

}

  编码实现约瑟夫环

/**
 * 环形链表解决约瑟夫环问题(间隔为3)
 */
public class Test3 {

    public static final int INVALID_DATA=http://www.mamicode.com/-1;>

  

链表下的约瑟夫环