【蓝桥云课】链表与队列

题目描述:
约瑟夫问题是个有名的问题:n个人围成一圈,从第一个开始报数,第m个出列,离开游戏,最后剩下一个。例如n=6,m=5,出列顺序是:5->4->6->2->3->1(剩下)

程序代码:
方法一:采用链表的方法

import java.util.Scanner;

public class JosephRing1 {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			Node head = new Node(1);//头结点
			Node temp = head;//最开始指向链表头
			for(int i=2;i<=n;i++) {
				temp.next = new Node(i);
				temp = temp.next;//依次构建链表
			}
			temp.next = head;//形成循环链表
			int count = 1;
			while(head.next!=head) {
				if(count==m-1) {
					System.out.print(head.next.val+"->");
					head.next = head.next.next;
					count = 1;
				} else {
					count++;
				}
				head = head.next;
			}
			System.out.println(head.val);
		}
	}
}

class Node{
	int val;
	Node next;
	public Node(int val) {
		this.val = val;
	}
}

方法二:采用队列的方法

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class JosephRing2 {
	
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		while(sc.hasNext()) {
			int n = sc.nextInt();
			int m = sc.nextInt();
			Queue<Integer> q = new LinkedList<Integer>();
			int count=1;
			for(int i=1;i<=n;i++) {
				q.offer(i);
			}
			while(!q.isEmpty()) {
				if(count==m) {
					System.out.print(q.poll()+"->");
					count=1;
				} else {
					count++;
					q.offer(q.poll());
				}
			}
			System.out.println();
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

CS_木成河

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

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

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

打赏作者

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

抵扣说明:

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

余额充值