zoukankan      html  css  js  c++  java
  • Leetcode 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 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 };
  • 相关阅读:
    linux下文件夹的创建、复制、剪切、重命名、清空和删除命令
    Linux 删除文件夹和创建文件的命令
    linux下拷贝整个目录
    星云大师:这十句话 我受用一生
    dex
    瘋耔java语言笔记
    VCC_VID_VTT等的含义
    一位数码管引脚
    android从应用到驱动之—camera(2)---cameraHAL的实现
    android从应用到驱动之—camera(1)---程序调用流程[转]
  • 原文地址:https://www.cnblogs.com/xiongqiangcs/p/4627301.html
Copyright © 2011-2022 走看看