算法刷题记录 Day9
Date: 2024.03.01
leetcode 232. 用栈实现队列
// 暴力解法,每次需要取数时,借用另一个stack倒序,用完恢复;
class MyQueue {
private:
stack<int> st1;
stack<int> st2;
public:
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int res = st2.top();
st2.pop();
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
return res;
}
int peek() {
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int res = st2.top();
while(!st2.empty()){
st1.push(st2.top());
st2.pop();
}
return res;
}
bool empty() {
return st1.empty();
}
};
// On解法,第一个栈接收输入,第二个栈在需要输出时,进行倒序和输出
class MyQueue {
private:
stack<int> st1;
stack<int> st2;
public:
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
if(st2.empty()){
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
int res = st2.top();
st2.pop();
return res;
}
int peek() {
if(st2.empty()){
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
}
int res = st2.top();
return res;
}
bool empty() {
return (st1.empty() && st2.empty());
}
};
lc 225. 用队列实现栈. 单队列和双队列实现方式一致。
class MyStack {
private:
queue<int> q1;
queue<int> q2;
int size;
public:
MyStack() {
size = 0;
}
void push(int x) {
q1.push(x);
size++;
}
int pop() {
int tmp = size - 1;
while(tmp--){
q1.push(q1.front());
q1.pop();
}
int v = q1.front();
q1.pop();
size--;
return v;
}
int top() {
int tmp = size - 1;
while(tmp--){
q1.push(q1.front());
q1.pop();
}
int v = q1.front();
q1.push(v);
q1.pop();
return v;
}
bool empty() {
return q1.empty();
}
};