约瑟夫问题 java描述

该博客介绍了一个使用Java解决约瑟夫环问题的代码实现。代码中定义了Node类表示节点,并创建了一个单链表来模拟人们围坐成圈的场景。通过Solution方法,按照给定的报数规则出列,最终输出所有出列顺序。博客着重展示了如何利用链表结构和循环条件来处理这一经典问题。
摘要由CSDN通过智能技术生成

问题描述:

设编号为1,2,…n的n个人围坐成一圈,约定编号为k的人从1开始报数,数到m的那个人出列,它的下一位又从1开始报数,数到m的那个人又出列,以此类推,直到所有人出列为止,得到一个出队编号的序列。

java代码:

public class Josephu {

    public static void main(String[] args) {
        Solution(5,1,2);
    }
    public static void Solution(int n, int k, int m) {
        SingleLinkedList list = new SingleLinkedList();
        list.StructList(n);
        Node temp = list.head;
        Node temp1  = list.head;
        while(--k != 0) {
            temp = temp.next;
        }
        while (temp1.next!=temp) {
            temp1 = temp1.next;
        }
        while(temp.next != temp) {
            for(int i=0;i<m-1;i++) {
                temp = temp.next;
                temp1 = temp1.next;
            }
            temp1.next = temp.next;
            System.out.println(temp);
            temp = temp.next;
        }
        System.out.println(temp);
    }
}
class Node {
    public int id;
    public Node next;

    public Node(int id) {
        this.id = id;
        this.next = null;
    }

    @Override
    public String toString() {
        return "{" +
                "id=" + id +
                '}';
    }
}
class SingleLinkedList {
    Node head = null;

    public void StructList(int length) {
        Node temp = null;
        Node first = null;
        for(int i= 0;i<length;i++ ) {
            if(i==0) {
                head = new Node(1);
                temp = head;
                first = head;
                head.next = first;
            } else {
                temp = head;
                first = head;
                while(temp.next!=first) {
                    temp = temp.next;
                }
                temp.next = new Node(i+1);
                temp = temp.next;
                temp.next = first;
            }
        }
    }
    public void list() {
        Node temp = head;
        while (temp.next != head) {
            System.out.println(temp);
            temp = temp.next;
        }
        System.out.println(temp);
    }
}

其实就是用对象对问题进行模拟实现。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Little BigUs

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值