问题描述:
设编号为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);
}
}
其实就是用对象对问题进行模拟实现。