Leetcode Implement Queue using Stacks

OpenSoucre發表於2015-07-07

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 toppeek/pop from topsize, 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).

題目意思:

  用棧實現佇列

解題思路:

  用兩個棧實現,一個棧用作佇列的出口,一個棧用作佇列的進口

擴充套件:

  c++ 的STL中佇列的實現不是用的棧,其實現原理是開闢一段記憶體,該記憶體中每個節點指向一段連續的記憶體空間,然後維護這些結點,具體參考《STL原始碼剖析》,面試時可能會問到STL佇列的實現方式。STL中還有個優先權佇列,其實現原理是用的堆資料結構實現的,堆排序演算法最好自己能寫。

原始碼:

 1 class Queue{
 2     stack<int> inStack, outStack;
 3 public:
 4     void  push(int x){
 5         inStack.push(x);
 6     }
 7     void pop(void){
 8         if(outStack.empty()){
 9             while(!inStack.empty()){
10                 outStack.push(inStack.top());
11                 inStack.pop();
12             }
13         }
14         outStack.pop();
15     }
16 
17     int peek(void){
18         if(outStack.empty()){
19             while(!inStack.empty()){
20                 outStack.push(inStack.top());
21                 inStack.pop();
22             }
23         }
24         return outStack.top();
25     }
26 
27     bool empty(void) {
28         return inStack.empty() && outStack.empty();
29     }
30 };

 

相關文章