日期:2014-05-20 浏览次数:20906 次
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;
}
}