码迷,mamicode.com
首页 > 其他好文 > 详细

链表下的约瑟夫环

时间:2017-07-12 15:10:33      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:point   turn   print   last   解决   list   div   pre   st3   

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

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=-1;

    public static final int SPACE=3;

    public static void main(String[] args) {

        Object[] obs = new Object[10];
        for (int i = 0; i < obs.length; i++) {
            obs[i]=i;
        }


        MyLinkedList2.MyNode node = new MyLinkedList2(obs).first;
        int point = 0;
        while (node.next!=null){

            if((int)node.w != INVALID_DATA){
                if(point==SPACE){
                    System.out.println(node.w);
                    //INVALID_DATA
                    node.w=INVALID_DATA;
                    point=0;

                }else {
                    point++;
                }
            }
            node=node.next;
        }
    }
}

  

链表下的约瑟夫环

标签:point   turn   print   last   解决   list   div   pre   st3   

原文地址:http://www.cnblogs.com/newstudent/p/7154978.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!