Merge pull request #2586 from MrYoungg/master

更新-0225.用队列实现栈/0150. 逆波兰表达式求值
This commit is contained in:
程序员Carl
2024-07-05 09:53:55 +08:00
committed by GitHub
2 changed files with 42 additions and 7 deletions

View File

@ -82,7 +82,7 @@
如动画所示: 如动画所示:
![150.逆波兰表达式求值](https://code-thinking.cdn.bcebos.com/gifs/150.逆波兰表达式求值.gif) ![150.逆波兰表达式求值](https://code-thinking.cdn.bcebos.com/gifs/150.逆波兰表达式求值.gif)
相信看完动画大家应该知道,这和[1047. 删除字符串中的所有相邻重复项](https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)是差不的,只不过本题不要相邻元素做消除了,而是做运算! 相信看完动画大家应该知道,这和[1047. 删除字符串中的所有相邻重复项](https://programmercarl.com/1047.删除字符串中的所有相邻重复项.html)是差不的,只不过本题不要相邻元素做消除了,而是做运算!
C++代码如下: C++代码如下:

View File

@ -72,6 +72,7 @@ class MyStack {
public: public:
queue<int> que1; queue<int> que1;
queue<int> que2; // 辅助队列,用来备份 queue<int> que2; // 辅助队列,用来备份
/** Initialize your data structure here. */ /** Initialize your data structure here. */
MyStack() { MyStack() {
@ -100,9 +101,28 @@ public:
return result; return result;
} }
/** Get the top element. */ /** Get the top element.
int top() { ** Can not use back() direactly.
return que1.back(); */
int top(){
int size = que1.size();
size--;
while (size--){
// 将que1 导入que2但要留下最后一个元素
que2.push(que1.front());
que1.pop();
}
int result = que1.front(); // 留下的最后一个元素就是要回返的值
que2.push(que1.front()); // 获取值后将最后一个元素也加入que2中保持原本的结构不变
que1.pop();
que1 = que2; // 再将que2赋值给que1
while (!que2.empty()){
// 清空que2
que2.pop();
}
return result;
} }
/** Returns whether the stack is empty. */ /** Returns whether the stack is empty. */
@ -126,14 +146,17 @@ C++优化代码
class MyStack { class MyStack {
public: public:
queue<int> que; queue<int> que;
/** Initialize your data structure here. */ /** Initialize your data structure here. */
MyStack() { MyStack() {
} }
/** Push element x onto stack. */ /** Push element x onto stack. */
void push(int x) { void push(int x) {
que.push(x); que.push(x);
} }
/** Removes the element on top of the stack and returns that element. */ /** Removes the element on top of the stack and returns that element. */
int pop() { int pop() {
int size = que.size(); int size = que.size();
@ -147,9 +170,21 @@ public:
return result; return result;
} }
/** Get the top element. */ /** Get the top element.
int top() { ** Can not use back() direactly.
return que.back(); */
int top(){
int size = que.size();
size--;
while (size--){
// 将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部
que.push(que.front());
que.pop();
}
int result = que.front(); // 此时获得的元素就是栈顶的元素了
que.push(que.front()); // 将获取完的元素也重新添加到队列尾部,保证数据结构没有变化
que.pop();
return result;
} }
/** Returns whether the stack is empty. */ /** Returns whether the stack is empty. */