题目描述:
约瑟夫问题是个有名的问题: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();
}
}
}