package Cap1;
import java.util.Iterator;
import edu.princeton.cs.introcs.StdOut;
import edu.princeton.cs.introcs.StdRandom;
public class CircleQueue<Item> implements Iterable<Item>{
/**
* @param args
*/
private Node last = null;
private class Node{
Item item;
Node next;
}
public void enqueue(Item item){
Node node = new Node();
node.item = item;
if(last != null){
node.next = last.next;
last.next = node;
}
else {
last = node;
last.next = last;
}
}
public Item dequeue(){
if(last.next == last){
Item item = last.item;
last = null;
return item;
}
Node t = last.next;
last.next = last.next.next;
t.next = null;
return t.item;
}
@Override
public Iterator<Item> iterator() {
// TODO Auto-generated method stub
return new CircleQueueIterator();
}
public class CircleQueueIterator implements Iterator<Item>{
private Node cur = last;
@Override
public boolean hasNext() {
// TODO Auto-generated method stub
return cur != null;
}
@Override
public Item next() {
// TODO Auto-generated method stub
if(cur.next != cur){
Node t = cur.next;
cur.next = cur.next.next;
t.next = null;
return t.item;
}
else{
Item item = cur.item;
cur = null;
return item;
}
}
@Override
public void remove() {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
CircleQueue<Double> cq = new CircleQueue<Double>();
for(int i=0;i<10;i++){
cq.enqueue(StdRandom.random()*100);
}
for(Double d : cq){
StdOut.print(d+"\n");
}
}
}
《算法(第四版)》 1.3.29 环形链表
最新推荐文章于 2022-11-14 18:20:25 发布