文章目录
- 前言
- 栈与队列知识点
- 一、 20. 有效的括号
- 二、1047. 删除字符串中的所有相邻重复项
- 三、150. 逆波兰表达式求值
- 总结
前言
一个本硕双非的小菜鸡,备战24年秋招,计划二刷完卡子哥的刷题计划,加油!
二刷决定精刷了,于是参加了卡子哥的刷题班,训练营为期60天,我一定能坚持下去,迎来两个月后的脱变的,加油!
推荐一手卡子哥的刷题网站,感谢卡子哥。代码随想录
栈与队列知识点
栈是一种后进先出( LIFO )的数据结构,它是一种线性的、有序的数据结构。栈的基本操作有两个,即入栈和出栈。入栈指将元素放入栈顶,出栈指将栈顶元素取出。栈的本质是一个容器,它可以存储任何类型的数据,但是栈的大小是固定的,因为它的元素只能在栈顶添加或删除。
队列是一种先进先出( FIFO )的数据结构,它与栈相似,也是一种线性的、有序的数据结构。队列的基本操作有三个,即入队、出队和查看队首元素。入队指将元素放入队尾,出队指将队首元素取出。队列的本质也是一个容器,它可以存储任何类型的数据,但是队列的大小也是固定的。
一、 20. 有效的括号
20. 有效的括号
Note:栈的应用
class MyQueue {
public:stack<int> stIn;stack<int> stOut;MyQueue() {}void push(int x) {stIn.push(x);}int pop() {if (stOut.empty()) {while(!stIn.empty()) {stOut.push(stIn.top());stIn.pop();}}int result = stOut.top();stOut.pop();return result;}int peek() {int res = this->pop();stOut.push(res);return res;}bool empty() {return stIn.empty() && stOut.empty();}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/
二、1047. 删除字符串中的所有相邻重复项
1047. 删除字符串中的所有相邻重复项
Note:记得输出结果之前字符串翻个个
class Solution {
public:string removeDuplicates(string s) {stack<char> res;for (char c : s) {if (res.empty() || res.top() != c)res.push(c);elseres.pop();}string result = "";while (!res.empty()) {result += res.top();res.pop();}reverse(result.begin(), result.end());return result;}
};
三、150. 逆波兰表达式求值
150. 逆波兰表达式求值
Note:逆波兰算法
class Solution {
public:int evalRPN(vector<string>& tokens) {stack<int> stk;int n = tokens.size();for(int i = 0; i < n; i++){string& token = tokens[i];if(token != "+" && token != "-" && token != "*" && token != "/"){stk.push(atoi(token.c_str()));}else{int num2 = stk.top();stk.pop();int num1 = stk.top();stk.pop();switch(token[0]){case '+':stk.push(num1 + num2);break;case '-':stk.push(num1 - num2);break;case '*':stk.push(num1 * num2);break;case '/':stk.push(num1 / num2);break;}}}return stk.top();}
};
总结
栈和队列是两种常见的数据结构,它们分别用于解决不同类型的问题。