import edu.princeton.cs.algs4.StdOut;
public class E1_4_28 {
public static void main(String[]args){
Stack<Integer>stack=new Stack<>();
for (int i=0;i<10;i++)
stack.push(i);
for (int i=0;i<10;i++)
StdOut.print(stack.pop()+" ");
}
public static class Stack<Item>{
private Queue<Item> queue=new Queue<>();
public boolean isEmpty(){return queue.isEmpty();}
public int size(){return queue.size();}
public void push(Item item){
queue.enqueue(item);
}
public Item pop(){
if (isEmpty())return null;
int N=size();
for (int i=0;i<N-1;i++)
queue.enqueue(queue.dequeue());
return queue.dequeue();
}
}
}
Queue的实现:
import edu.princeton.cs.algs4.StdIn;
import edu.princeton.cs.algs4.StdOut;
import java.util.Iterator;
public class Queue<Item> implements Iterable<Item> {
public static void main(String[]args){
//Create a queue and enqueue/dequeue strings.
Queue<String> q=new Queue<>();
while (!StdIn.isEmpty()){
String item=StdIn.readString();
if (!item.equals("-"))
q.enqueue(item);
else if (!q.isEmpty()) StdOut.print(q.dequeue()+" ");
}
StdOut.println("("+q.size()+" left on queue)");
}
private Node first; //link to least recently added node
private Node last; //link to most recently added node
private int N; //number of items on the queue
private class Node{
//nested class to define nodes
Item item;
Node next;
}
public Queue(){
first=null;
last=null;
N=0;
}
public Queue(Queue<Item> q){//1.3.41
int N=q.size();
for (int i=0;i<N;i++){
Item item=q.dequeue();
enqueue(item);
q.enqueue(item);
}
}
public boolean isEmpty(){
return first==null;//Or:N= =0.
}
public int size(){ return N;}
public void enqueue(Item item){
//Add item to the end of the list.
Node oldlast=last;
last=new Node();
last.item=item;
last.next=null;
if (isEmpty())first=last;
else oldlast.next=last;
N++;
}
public Item dequeue(){
//Remove item from the beginning of the list.
Item item=first.item;
first=first.next;
if (isEmpty())last=null;
N--;
return item;
}
public Iterator<Item> iterator(){
return new QueueIterator();
}
private class QueueIterator implements Iterator<Item>{
private Node current=first;
public boolean hasNext(){
return current!=null;
}
public void remove(){ }
public Item next(){
Item item=current.item;
current=current.next;
return item;
}
}
}