day9 – 栈与队列part01
理论基础:栈与队列理论基础 | 栈 | 队列 | 容器适配器 | 代码随想录
232.用栈实现队列
- 力扣题目链接:232. 用栈实现队列 - 力扣(LeetCode)
- 文章讲解:232.用栈实现队列 | 栈 | 队列 | 模拟 | 代码随想录
- 视频讲解:栈的基本操作! | LeetCode:232.用栈实现队列_哔哩哔哩_bilibili
用一个输入栈,一个输出栈来实现
public class MyQueue {
Stack<int> i;
Stack<int> o;
public MyQueue() {
i = new Stack<int>();
o = new Stack<int>();
}
public void Push(int x) {
if (i.Count == 0){
while(o.Count > 0){
i.Push(o.Pop());
}
i.Push(x);
}
else if (o.Count == 0){
i.Push(x);
}
}
public int Pop() {
if (o.Count == 0){
while(i.Count > 1){ //pop第一个
o.Push(i.Pop());
}
return i.Pop();
}
else //(i.Count == 0)
{
return o.Pop();
}
}
public int Peek() {
if (o.Count == 0){
while(i.Count > 0){
o.Push(i.Pop());
}
return o.Peek();
}
else//(i.Count == 0)
{
return o.Peek();
}
}
public bool Empty() {
if (i.Count == 0 && o.Count == 0) return true;
return false;
}
}
/**
* 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();
*/
225.用队列实现栈
- 力扣题目链接:225. 用队列实现栈 - 力扣(LeetCode)
- 文章讲解:225. 用队列实现栈 | 队列 | 栈 | 模拟 | 代码随想录
- 视频讲解:队列的基本操作! | LeetCode:225. 用队列实现栈_哔哩哔哩_bilibili
用一个队列就可实现:
思路是首尾相接
动画:

public class MyStack {
Queue<int> q;
public MyStack() {
q = new Queue<int>();
}
public void Push(int x) {
q.Enqueue(x);
}
public int Pop() {
int count = q.Count;
while (count-- > 1){
q.Enqueue(q.Dequeue());
}
return q.Dequeue();
}
public int Top() {
int count = q.Count;
while (count-- > 1){
q.Enqueue(q.Dequeue());
}
int res = q.Peek();
q.Enqueue(q.Dequeue());
return res;
}
public bool Empty() {
if (q.Count == 0) return true;
return false;
}
}
20.有效的括号
- 力扣题目链接:20. 有效的括号 - 力扣(LeetCode)
- 文章讲解:20. 有效的括号 | 栈 | 括号匹配 | 对称匹配 | 代码随想录
- 视频讲解:栈的拿手好戏!| LeetCode:20. 有效的括号_哔哩哔哩_bilibili
很直观的解法动画:

public class Solution {
public bool IsValid(string s) {
Stack<char> s1 = new Stack<char>();
foreach (char i in s){
if (i == '(' || i == '[' || i == '{') s1.Push(i);
else if (i == ')'){
//记得检查非空,不然Peek()报错
if (s1.Count == 0) return false;
if (s1.Peek() != '(') return false;
else s1.Pop();
}
else if (i == ']'){
if (s1.Count == 0) return false;
if (s1.Peek() != '[') return false;
else s1.Pop();
}
else{ //if (i == '}')
if (s1.Count == 0) return false;
if (s1.Peek() != '{') return false;
else s1.Pop();
}
}
if (s1.Count != 0) return false;
return true;
}
}
1047.删除字符串中的所有相邻重复项
- 力扣题目链接:1047. 删除字符串中的所有相邻重复项 - 力扣(LeetCode)
- 文章链接:1047. 删除字符串中的所有相邻重复项 | 栈 | 相邻重复项 | 匹配问题 | 代码随想录
- 视频链接:栈的好戏还要继续!| LeetCode:1047. 删除字符串中的所有相邻重复项_哔哩哔哩_bilibili
思路和上面的很像:
public class Solution {
public string RemoveDuplicates(string s) {
Stack<char> s1 = new Stack<char>();
foreach (char i in s){
if (s1.Count == 0) s1.Push(i);
else{
if(s1.Peek() == i) s1.Pop();
else s1.Push(i);
}
}
return new string(s1.Reverse().ToArray());
}
}

1257

被折叠的 条评论
为什么被折叠?



