/**
* Filename : StackWithTwoQueues.java
* Dependency: None
* Author : Sheng Yu (codesays.com)
* Create at : 2014-08-03
* JDK used : 1.7
* Change log: None
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StreamTokenizer;
import java.util.NoSuchElementException;
import java.util.Queue;
import java.util.concurrent.LinkedBlockingQueue;
/**
* @author Sheng Yu (codesays.com)
* @param <T>: the type of dealing data.
*/
class Stack<T> {
// main queue always stores the elements.
// swap is used in pop() function to hold the elements temporarily.
private Queue<T> main = new LinkedBlockingQueue<T>();
private Queue<T> swap = new LinkedBlockingQueue<T>();
// Used in pop() function to exchange he main and swap queues.
private Queue<T> temp = null;
/**
* @param item: to push into the stack.
*/
public void push(T item) {
main.add(item);
}
/**
* @return T: remove and return the most recent element in the stack.
* @throws NoSuchElementException: pop when queue is empty.
*/
public T pop() throws NoSuchElementException {
T result = null;
// swap is always empty at the beginning of popping.
if (main.size() == 0) {
throw new NoSuchElementException("Queue is empty");
}
// Move all data in main queue to swap, except the most recent one.
while (main.size() > 1) {
swap.add(main.remove());
}
// Get the most recent element.
result = main.remove();
// Exchange main and swap queue, so that we always push new data into
// main queue.
temp = main;
main = swap;
swap = temp;
return result;
}
}
public class StackWithTwoQueues {
/**
* Stub for test
* @param args
* @throws IOException
* @throws NoSuchElementException
* @throws IllegalArgumentException
*/
public static void main(String[] args)
throws IOException, NoSuchElementException, IllegalArgumentException {
StreamTokenizer st = new StreamTokenizer(new BufferedReader(
new InputStreamReader(System.in)));
Stack<Integer> test = new Stack<Integer>();
boolean popSuc = true;
Integer res = 0;
String instruction = null;
while (st.nextToken() != StreamTokenizer.TT_EOF) {
instruction = st.sval;
if (instruction.equalsIgnoreCase("POP")) {
try{
popSuc = true;
res = test.pop();
}
catch (NoSuchElementException e) {
// Failed to pop something.
popSuc = false;
System.out.println(-1);
}
if (popSuc) {
// Successful to pop something.
System.out.println(res);
}
}
else if (instruction.equalsIgnoreCase("PUSH")){
st.nextToken();
test.push((int)st.nval);
}
else {
throw new IllegalArgumentException(instruction + "is invalid.");
}
}
}
}