Popular Posts

Sunday, March 27, 2011

Queue
 Using 
Stacks


Describe a queue data structure that is implemented using one or more stacks.

Don't worry about running time.Write the enqueue and dequeue operations for the queue.

answer:
You can use two stacks: an "incoming" stack and an "outgoing" stack.
The enqueue and dequeue operations would look like this(in Java):
Stack in;
Stack out;
void enqueue(int value) {
while (!out.isEmpty())
in.push(out.pop());
in.push(value);
}
int dequeue() {
while (!in.isEmpty())
out.push(in.pop());
return out.pop();
}

1 comment: