第2周 第4天 力扣刷题|栈和队列

用栈实现队列

思路:push操作比较简单,主要难在pop操作。要知道栈是先进后出,而队列是先进先出

题目给了一个思路,就是使用输入栈和输出栈,当pop时,把输入栈的输入先都放到输出栈中,那么此时输出栈的栈顶元素就是我们想要pop出去的元素,我们可以记录一下这个元素,并把这个元素从输出栈从pop出去,然后在依次把输出栈的元素push到输入栈中(这是我自己想的思路,跟代码随想录上有所不同)

 class MyQueue {
 public:
     stack stack_in;
     stack stack_out;
     MyQueue() {
 ​
     }
     
     void push(int x) {
         stack_in.push(x);
     }
     
     int pop() {
         while (!stack_in.empty())
         {
             int x = stack_in.top();
             stack_in.pop();
             stack_out.push(x);
         }
         int result = stack_out.top();
         stack_out.pop();
         while (!stack_out.empty())
         {
             int y = stack_out.top();
             stack_out.pop();
             stack_in.push(y);
         }
         return result;
     }
     
     int peek() {
         while (!stack_in.empty())
         {
             int x = stack_in.top();
             stack_in.pop();
             stack_out.push(x);
         }
         int result = stack_out.top();
         while (!stack_out.empty())
         {
             int y = stack_out.top();
             stack_out.pop();
             stack_in.push(y);
         }
         return result;
     }
     
     bool empty() {
         if (stack_in.empty())
             return true;
         return false;
     }
 };

用队列实现栈

思路:同样也是push操作比较简单,pop操作比较难。

这里我们只需用一个队列即可,假设队列中元素个数为n,将前n-1个元素先pop出去,再push进来,即将队列中前n-1个元素重新添加到队列尾部

 class MyStack {
 public:
     queue q;
     MyStack() {
 ​
     }
     
     void push(int x) {
         q.push(x);
     }
     
     int pop() {
         int size = q.size();
         for (int i = 0; i < size - 1; i++)
         {
             int x = q.front();
             q.pop();
             q.push(x);
         }
         int result = q.front();
         q.pop();
         return result;
     }
     
     int top() {
         int size = q.size();
         for (int i = 0; i < size - 1; i++)
         {
             int x = q.front();
             q.pop();
             q.push(x);
         }
         int result = q.front();
         int x = q.front();
         q.pop();
         q.push(x);
         return result;
     }
     
     bool empty() {
         if (q.empty())
             return true;
         return false;
     }
 };

你可能感兴趣的:(笔记,java,servlet,开发语言)