Implement the following operations of a queue using stacks.
push(x) – Push element x to the back of queue.
pop() – Removes the element from in front of queue.
peek() – Get the front element.
empty() – Return whether the queue is empty.
Notes:
You must use only standard operations of a stack – which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
解法1:Two Queue
stack和queue的区别是前者是FILO, 后者是FIFO, 如果用另外一个stack去反倒回来就得到了queue一样的效果。
实现起来,用一个buffer stack存储应该的顺序,peek和pop都应该从buffer中取,如果读取buffer的时候为空的话,则需要把数据从原stack移到buffer。
C++
Java
只有在push的时候,如果当前的stack里面存在元素的话,先把元素存在另外一个stack里面。然后把要push的元素push了之后再把buffer里面的元素放回stack。