约瑟夫问题(单向循环对列)

题目描述:
在这里插入图片描述题目解析:
该题是是基于单向循环队列实现的,其实简单点来说就是隔两个结点删一个结点,直至剩下两个结点,然后把两个结点中存储的数据输出。

解题步骤:
1.定义结点内部类,用于描述结点

2.创建关于创建链表的构造函数,通过for循环把结点位置一确定,每个结点的数据域中存储该结点的位置

3.编写函数删除指定位置的元素,将最终剩余的两个节点的位置一同放入一个线性表中,返回该线性表。如下图所示删除:
在这里插入图片描述完整代码:

package Ds02.动态链表;

import DS01.动态数组.ArrayList;
import DS01.动态数组.List;
//约瑟夫环  真实头结点  循环一类的都是基于循环链表
public class JosephusLoop {
    private Node head;
    private Node rear;
    private int size;
    public JosephusLoop(int count){
        head=new Node(1,null);
        rear=head;
        rear.next=head;
        for(int i=0;i<=count;i++){
            rear.next=new Node(i,rear.next);//尾插法
            rear=rear.next;
        }
        size=count;
    }
    public List<Integer> getSurvivePosition(){ //List接口可用好几个类来实现,可用一个线性表把结果存储起来
                                                //然后返回一个线性表
        ArrayList<Integer> list=new ArrayList<>();
        Node p=head;
        while (size>2){
            p=p.next;
            Node del=p.next;
            if(del==head){
                head=head.next;
            }
            if(del==rear){
                rear=p;
            }
            p.next=del.next;
            p=p.next;
            size--;
        }
        list.addLast(p.position);
        list.addLast(p.next.position);
        return list;
    }
    private class Node{
        int position;
        Node next;
        public Node(){}
        public Node(int position,Node next){
            this.position=position;
            this.next=next;
        }
    }
    public static void main(String[] args){
        JosephusLoop jp=new JosephusLoop(41);
        List<Integer> list=jp.getSurvivePosition();
        System.out.println(list);
    }
}


发布了49 篇原创文章 · 获赞 4 · 访问量 899

猜你喜欢

转载自blog.csdn.net/weixin_45404784/article/details/103586013