232.用栈实现队列
题目链接/文章讲解/视频讲解:代码随想录
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();
}
};
用栈实现队列其实很简单用俩个栈就行了 假设我要的队列是12345,那么出列就是12345 我要两个栈就是向第一个栈插入12345,然后出栈就是54321然后再插入第二个栈就是54321出栈就是12345
225. 用队列实现栈
题目链接/文章讲解/视频讲解:代码随想录
class MyStack {
public:
queue<int> que;
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
que.push(x);
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
int size = que.size();
size--;
while (size--) {
que.push(que.front());
que.pop();
}
int result = que.front();
que.pop();
return result;
}
/** Get the top element. */
int top() {
return que.back();
}
/** Returns whether the stack is empty. */
bool empty() {
return que.empty();
}
};
;其实用一个队列就可以实现栈了就比如队列12345先插入队列的首元素就变成123451之后弹出首元素就变成23451之后持续这个操作直到51234最后记录这个首元素5最后弹出5就行了
20. 有效的括号
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
bool isValid(string s) {
if (s.size() % 2 != 0) return false;
stack<char> st;
for (int i = 0; i < s.size(); i++) {
if (s[i] == '(') st.push(')');
else if (s[i] == '{') st.push('}');
else if (s[i] == '[') st.push(']');
else if (st.empty() || st.top() != s[i]) return false;
else st.pop(); }
return st.empty();
}
};
首先要判断括号的是否是奇数如果是则返回false然后定义一个栈之后进入for循环当遍历完括号数组之后结束循环之后每遍历到{(这种的就插入对应的})进入栈里面当发现不是{类似这种时候进行判断判断栈里面是否为空或者判断栈的尾部和此时遍历到的数组元素是否相等,如果不相等则返回false再反之就弹出栈顶元素
1047. 删除字符串中的所有相邻重复项
题目链接/文章讲解/视频讲解:代码随想录
class Solution {
public:
string removeDuplicates(string S) {
string result;
for(char s : S) {
if(result.empty() || result.back() != s) {
result.push_back(s);
}
else {
result.pop_back();
}
}
return result;
}
};
首先建立一个栈,建立之后进入for循环之后在判断栈是否为空如果为空则进栈或者栈顶元素等不等于当前遍历元素如果不等也进栈如果以上反之则弹出栈