leetcode-225 用队列实现栈

leetcode-225 用队列实现栈

1.题目

使用队列的基本操作实现栈的共,可以使用list或者双端队列deque

2.解题方法

  • 使用vector实现,维持一个top数值代表栈顶元素的index,每次插入、删除元素会导致top元素的变化
  • 使用deque实现时,原理同vector,插入和删除元素都在同一端
  • 使用queue实现时,因为队列只支持在一端添加元素,另一端删除元素,所以采用两个数字来实现,建立一个data队列,每次插入元素将值放入data中,建立一个help数组,执行pop方法时,先将data队列中的除第一个元素外全转移至help队列中,再执行data.pop(),此时pop出的元素即是栈顶元素,再交换help和data队列。执行top方法与pop方法类似,只是最后一个元素也要放入help数组中。
    lc225.png

3.Code

使用vector实现

 class MyStack {
 public:
  /** Initialize your data structure here. */
  int top_index;
  vector<int> data;
  MyStack() { top_index = -1; }

  /** Push element x onto stack. */
  void push(int x) {
    data.push_back(x);
    top_index++;
  }

  /** Removes the element on top of the stack and returns that element. */
  int pop() {
    int x = data[top_index];
    data.pop_back();
    top_index--;
    return x;
  }

  /** Get the top element. */
  int top() { return data[top_index]; }

  /** Returns whether the stack is empty. */
  bool empty() { return top_index < 0 ? true : false; }
};

使用queue实现

class MyStack {
 public:
  /** Initialize your data structure here. */
  queue<int> data;
  queue<int> help;
  MyStack() {}

  /** Push element x onto stack. */
  void push(int x) { data.push(x); }

  /** Removes the element on top of the stack and returns that element. */
  int pop() {
    if (data.size() == 1) {
      int x = data.front();
      data.pop();
      return x;
    } else {
      while (data.size() != 1) {
        help.push(data.front());
        data.pop();
      }
      int x = data.front();
      data.pop();
      queue<int> temp = data;
      data = help;
      help = temp;
      return x;
    }
  }

  /** Get the top element. */
  int top() {
    if (data.size() == 1) {
      return data.front();
    } else {
      while (data.size() != 1) {
        help.push(data.front());
        data.pop();
      }
      int x = data.front();
      help.push(data.front());
      data.pop();
      queue<int> temp = data;
      data = help;
      help = temp;
      return x;
    }
  }

  /** Returns whether the stack is empty. */
  bool empty() { return help.size() == 0 ? true : false; }
};
posted @ 2021-10-16 10:37  流光之中  阅读(41)  评论(0)    收藏  举报