算法day28 用栈实现队列

题目描述

思路:双栈
我们知道,队列的规则是先进先出,栈的规则是先进后出,要用栈实现队列的相关操作,我们只需要建立两个栈,一个栈用作输入,一个栈用作输出。当输入时将输入的数据存储在输入栈中,当输出或要查看队列的队首时,我们更新输出栈,然后使用输出栈进行相关的操作。

代码如下

class MyQueue {
public:
stack<int> stack_in;
stack<int> stack_out;
MyQueue() {
    
}

void push(int x) {//入队操作
    stack_in.push(x);
}

int pop() {//出队操作
    if(stack_in.empty()&&stack_out.empty()){
        return -1;
    }
    if(stack_out.empty()){//持续更新输出栈
        while(!stack_in.empty()){
            stack_out.push(stack_in.top());
            stack_in.pop();
        }   
    }
        int x =  stack_out.top();//返回队头元素
        stack_out.pop();//出栈
        return x; 
}

int peek() {
  int res = this -> pop();//调用上面完成的出队函数
  stack_out.push(res);
  return res;
}

bool empty() {
    if(stack_in.empty()&&stack_out.empty()){
        return true;
    }
    return false;
}
};

时间复杂度:O(1)
空间复杂度:O(n)

END

posted on 2025-05-14 14:06  sakura430  阅读(9)  评论(0)    收藏  举报