• LeetCode OJ:Implement Stack using Queues(队列实现栈)


    Implement the following operations of a stack using queues.

    • push(x) -- Push element x onto stack.
    • pop() -- Removes the element on top of the stack.
    • top() -- Get the top element.
    • empty() -- Return whether the stack is empty.

    Notes:

    • You must use only standard operations of a queue -- which means only push to backpeek/pop from frontsize, and is empty operations are valid.
    • Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
    • You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack)

    类似上一题的两个栈实现队列,但是有点不同,具体的见下面的注释:

     1 class Stack {
     2 public:
     3     // Push element x onto stack.
     4     void push(int x) {
     5         q1.push(x);
     6     }
     7 
     8     // Removes the element on top of the stack.
     9     void pop() {
    10         int tmp = q1.front();//注意这里的实现和双栈实现队列的方式是不相同的
    11         q1.pop();
    12         while(!q1.empty()){
    13             q2.push(tmp);
    14             tmp = q1.front();
    15             q1.pop();
    16         }
    17         swap(q1,q2);
    18     }
    19 
    20     // Get the top element.
    21     int top() {
    22         int tmp = q1.front();
    23         q1.pop();
    24         while(!q1.empty()){
    25             q2.push(tmp);
    26             tmp = q1.front();
    27             q1.pop();
    28         }
    29         q2.push(tmp);
    30         swap(q1, q2);//用swap即可,无须再向上次那样再倒回去
    31         return tmp;
    32     }
    33 
    34     // Return whether the stack is empty.
    35     bool empty() {
    36         return q1.empty();            
    37     }
    38 private:
    39     queue<int> q1;
    40     queue<int> q2;
    41 };
  • 相关阅读:
    USACO 2.1 Hamming Codes
    USACO 2.1 Healthy Holsteins
    USACO 2.1 Sorting a Three-Valued Sequence
    USACO 2.1 Ordered Fractions
    USACO 2.1 The Castle
    USACO 1.5 Superprime Rib
    1145: 零起点学算法52——数组中删数II
    1144: 零起点学算法51——数组中删数
    1143: 零起点学算法50——数组中查找数
    1142: 零起点学算法49——找出数组中最大元素的位置(下标值)
  • 原文地址:https://www.cnblogs.com/-wang-cheng/p/5014160.html
Copyright © 2020-2023  润新知