Thursday, March 7, 2013

[Cracking the Code Interview 4th Edition] 3.5

Implement a MyQueue class which implements a queue suing two stacks.

Thought:
Queue is a FIFO structure.
Stack is a LIFO structure.

When pushing, we push Node in S1.
When popping or peeking, we check S2, if S2 is not empty, pop from s2.
If S2 is empty, pop s1 and push it into S2 until s1 is empty, and then pop from s2.

No comments:

Post a Comment