import java.util.LinkedList;
import java.util.Queue;
/**
* Interface declaring the operations supported by a Stack
* @author Prateek
*
* @param <T> : Type to the Elements to be inserted into Stack
*/
interface IStack<T> {
void push(T item);
T pop();
T peek();
boolean isEmpty();
}
/**
* Implement Stack using Queues
* @author Prateek
*/
class StackwithQueues implements IStack<Integer> {
//for pushing data
private Queue<Integer> queue1 = new LinkedList<Integer>();
// used for reversing the data of queue1 and flipping of queues
private Queue<Integer> queue2 = new LinkedList<Integer>();
/**
* Push operation of Stack
* Item pushed into Queue1
*/
@Override
System.
out.
println("Push : "+item
); queue1.offer(item);
}
/**
* Pop operation of Stack
* last item of queue1 is returned,
* order is reversed using queue2
*/
@Override
if(!queue1.isEmpty())
{
while (!queue1.isEmpty())
{
item=queue1.poll();
if(!queue1.isEmpty())
queue2.add(item);
}
flip();
}
else
System.
out.
println("Stack is Empty"); System.
out.
println("Poped : "+ item
); return item;
}
/**
* Peek operation, similar to pop ,
* with slight modification
*/
@Override
while (!queue1.isEmpty()) {
item=queue1.poll();
queue2.add(item);
}
flip();
System.
out.
println("Peek : "+ item
); return item;
}
@Override
public boolean isEmpty() {
return queue1.isEmpty();
}
/**
* Flipping of Queues
*/
public void flip(){
Queue<Integer> tQueue= queue1;
queue1=queue2;
queue2 = tQueue;
}
public static void main
(String[] args
) { StackwithQueues obj=new StackwithQueues();
obj.push(1);
obj.push(2);
obj.push(3);
obj.push(4);
obj.peek();
obj.pop();
obj.pop();
obj.peek();
obj.pop();
obj.pop();
obj.pop();
}
}
aW1wb3J0IGphdmEudXRpbC5MaW5rZWRMaXN0OwppbXBvcnQgamF2YS51dGlsLlF1ZXVlOwovKioKICogSW50ZXJmYWNlIGRlY2xhcmluZyB0aGUgb3BlcmF0aW9ucyBzdXBwb3J0ZWQgYnkgYSBTdGFjawogKiBAYXV0aG9yIFByYXRlZWsKICoKICogQHBhcmFtIDxUPiA6IFR5cGUgdG8gdGhlIEVsZW1lbnRzIHRvIGJlIGluc2VydGVkIGludG8gU3RhY2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