Friday, March 25, 2011
Wednesday, March 9, 2011
Simulating queue using stack...
Problem statement: we are given one stack and we have to implement the queue using this stack means enqueue(insert into stack) and dequeue ( pop from stack) should behave as queue. No additional stack should be used.
This can be done using Operating system stack by using recursion.
This can be done using Operating system stack by using recursion.
public class SimulatedQueue < E > { private java.util.Stack < E > stack = new java.util.Stack < E >(); public void insert(E elem) { if (!stack.empty()) { E topElem = stack.pop(); insert(elem); stack.push(topElem); } else stack.push(elem); } public E remove() { return stack.pop(); } }
Subscribe to:
Posts (Atom)