程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode] Implement Queue using Stacks

[LeetCode] Implement Queue using Stacks

編輯:C++入門知識

[LeetCode] Implement Queue using Stacks


Implement Queue using Stacks

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).

      解題思路:

      用兩個棧來模擬隊列。其中一個棧做緩存之用,另外一個棧只接受。push操作,直接放入接收之棧中。pop操作,若緩存棧存在數據,則從緩存棧中彈出。若緩存棧為空,則將接收棧的數據彈出並插入到緩存棧中,再從緩存棧中彈出。peek操作與pop操作類似。當且僅當兩個棧都為空時,empty才返回true。

       

      class Queue {
      public:
          // Push element x to the back of queue.
          void push(int x) {
              stacks[0].push(x);
          }
      
          // Removes the element from in front of queue.
          void pop(void) {
              if(stacks[1].empty()){
                  while(!stacks[0].empty()){
                      stacks[1].push(stacks[0].top());
                      stacks[0].pop();
                  }
              }
              stacks[1].pop();
          }
      
          // Get the front element.
          int peek(void) {
              if(stacks[1].empty()){
                  while(!stacks[0].empty()){
                      stacks[1].push(stacks[0].top());
                      stacks[0].pop();
                  }
              }
              return stacks[1].top();
          }
      
          // Return whether the queue is empty.
          bool empty(void) {
              return stacks[0].empty() && stacks[1].empty();
          }
          
      private:
          stack stacks[2];
      };


       

      版權聲明:本文為博主原創文章,未經博主允許不得轉載。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved