求高手解答~
有16个人围成一圈(编号0-16),从0号开始从1报数,凡是报到3的倍数的人离开圈子,然后再数下去,直到只剩下一个人为止。编写一个java程序,求出此人原来的位置是多少号? (我感觉是不是应该用FOR循环,然后用IF 判断。关键之后的第2圈呢,然后怎么能知道原来的位置呢?)
[解决办法]
写了下,献丑了,自己建立个DoubleLinkedList
import java.util.NoSuchElementException;
public class JosephusRing {
public static void main(String[] args) {
ClinkedList c = new ClinkedList();
for (int i = 0; i < 16; i++) {
Node q = new Node(i);
c.insert(q, c.dummy.prev);
}
for (Node t = c.getFirst(); !c.isEmpty(); t = t.next.next) {
if(c.dummy==t.next)
t=t.next;
System.out.println(t.next.elem);
c.delete(t.next);
}
}
}
class Node {
Node prev, next;
Object elem;
public Node(Object i) {
elem = i;
}
}
class ClinkedList {
Node dummy;
public void insert(Node p, Node q) {
p.next = q;
p.prev = q.prev;
p.next.prev = p;
p.prev.next = p;
}
public void delete(Node p) {
if (p == dummy)
delete(dummy.next);
else {
p.prev.next = p.next;
p.next.prev = p.prev;
}
}
public boolean isEmpty() {
return dummy.next == dummy;
}
public Node getFirst() {
if (isEmpty())
throw new NoSuchElementException();
return dummy.next;
}
public Node getLast() {
if (isEmpty())
throw new NoSuchElementException();
return dummy.prev;
}
public ClinkedList() {
dummy = new Node(null);
dummy.next = dummy;
dummy.prev = dummy;
}
}