单向环形链表

约瑟夫问题:已知有n个人(分别编号为1,2,3…n)围坐成一圈,从第一个人开始报数,报到数m的人出圈;再从下一个人开始重新报数,报到m的人出圈;直至剩下最后一个人的时候游戏结束。输出剩下的人的原始编号。

 

利用单向环形链表解决约瑟夫问题

class Node {//该节点省略data域
    public int no;
    public Node next;

    public Node(int no) {
        if (no >= 0) {//要求no要大于0
            this.no = no;
        }
    }

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                '}';
    }
}

public class CircleSingleLinkedList {
    private Node first = null;

    public void add(int nums) {//构建单向环形链表,nums是创建节点的总个数
        if (nums < 1) {
            return;
        }
        Node cur = null;
        for (int i = 1; i <= nums; i++) {
            Node node = new Node(i);
            if (i == 1) {
                first = node;
                first.next = first;
                cur = first;
            } else {
                cur.next = node;
                node.next = first;
                cur = node;
            }
        }
    }

    public void show() {//打印单向环形链表
        if (first == null) {
            return;//链表为空
        }
        Node cur = first;
        while (true) {
            System.out.println(cur);
            if (cur.next == first) {
                return;//遍历完毕
            }
            cur = cur.next;
        }
    }

    //start:开始节点,count:报数的次数,nums:有效节点总个数
    public void count(int start, int count, int nums) {//解决约瑟夫问题
        if (first == null || start < 1 || start > nums) {
            return;//数组为空或参数有误
        }
        for (int i = 0; i < start - 1; i++) {
            first = first.next;//指向开始报数的节点
        }
        Node helper = first;//辅助指针,帮助节点出圈
        while (true) {
            if (helper.next == first) {
                break;//使helper在first前一个位置,即单向环形链表最后一个位置
            }
            helper = helper.next;
        }
        while (true) {
            if (helper == first) {//说明单向环形链表只剩一个节点
                break;
            }
            for (int i = 0; i < count - 1; i++) {
                first = first.next;
                helper = helper.next;
            }
            System.out.print(first.no + "出链表");//first指向的节点出链表
            first = first.next;//指向下一个要报数的节点
            helper.next = first;
        }
        System.out.println("剩余" + first.no);//最后留在链表节点的编号
    }
}
posted @   半条咸鱼  阅读(16)  评论(0编辑  收藏  举报
(评论功能已被禁用)
相关博文:
阅读排行:
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 没有源码,如何修改代码逻辑?
· PowerShell开发游戏 · 打蜜蜂
· 在鹅厂做java开发是什么体验
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
点击右上角即可分享
微信分享提示