总结先放在前面:
栈和队列是可以互相转换使用的,其中两个栈可以实现一个队列,而一个队列就可以实现栈。
栈通常用来解决匹配问题,比如说NO.20. 有效的括号和NO.1047. 删除字符串中的所有相邻重复项以及NO.150. 逆波兰表达式求值
对于队列,应该通过 NO.239. 滑动窗口最大值 来学习单调队列(实际上由于C#不像C++或者java一样有方法可以获取队列的末尾值getLast()和removeLast()之类的方法,我们需要使用List来进行替代),这里主要是学习它的想法
解答栈与队列时的一些小技巧与注意点:
栈对于在遇到字符串以及一个有关于处理优先级顺序方面的题目很有用,比如说括号匹配,逆波兰表达式
队列需要学会单调队列的思想,NO.239. 滑动窗口最大值 主要提示了队列在窗口类题目的应用
题目实战
1.NO.232.用栈实现队列
public class MyQueue {
Stack<int> st1=new Stack<int>(); //st1用来保存数据
Stack<int> st2=new Stack<int>(); //st2用来保存顺序排好的数据
/** Initialize your data structure here. */
public MyQueue() {
}
/** Push element x to the back of queue. */
public void Push(int x) {
//
st1.Push(x);
}
/** Removes the element from in front of queue and returns that element. */
public int Pop() {
while(st1.Count!=0){
st2.Push(st1.Pop());
}
int tmp=st2.Pop();
while(st2.Count!=0){
st1.Push(st2.Pop());
}
return tmp;
}
/** Get the front element. */
public int Peek() {
//队列开头的元素,就是栈最底下的元素。
while(st1.Count!=0){
//把st1全部压到st2中,顺序就对了
st2.Push(st1.Pop());
}
int tmp= st2.Peek();
while(st2.Count!=0){
//复原
st1.Push(st2.Pop());
}
return tmp;
}
/** Returns whether the queue is empty. */
public bool Empty() {
if(st1.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();
*/
2.NO.225. 用队列实现栈
其实队列实现一个栈只需要知道队列里面有多少个元素就行了,通过不断地出和进来改变顺序
public class MyStack {
Queue<int> que=new Queue<int>();
int count=0; //count用来保存当前队列中元素的个数
/** Initialize your data structure here. */
public MyStack() {
}
/** Push element x onto stack. */
public void Push(int x) {
que.