Nine Chapters count judges Net-original website
http://www.jiuzhang.com/problem/49/
Topics
Specify that you can only use the data structure stack (support pop, push), how to use the stack to simulate a queue of pop and push?
Tip: You can use multiple stacks.
Requirements: The averaging complexity of each operation needs to be O (1)
Online test
http://lintcode.com/zh-cn/problem/implement-queue-by-stacks/
AnswerUse two stacks, stack1 and Stack2. The operation for the queue corresponds to the following:
Queue.Push:push to Stack1
Queue.pop: If Stack2 is non-null, stack2.pop otherwise pops all the numbers in the Stack1 to Stack2 (equivalent to the order upside down), then Stack2.pop ()
Each number goes in and out of Stack1 and Stack2 1 times, so the averaging complexity of two operations is O (1)
Nine-chapter algorithm surface test 49 using stacks to implement the queue