学数据结构的时候,我们总会遇到栈和队列,今天就说说栈和队列的异同。
相同点:
1. 都是线性结构
2. 操作模式存在限制
重点内容 3. 都可以通过顺序表和链表进行结构实现
4. 插入删除的时间复杂度相同(都是O(1)),空间复杂度也相同
不同点:
1. 栈是后进先出原则,而队列是先进先出
2. 栈只允许在末端进行插入删除,而队列是在队首进行插入删除
他们的不同点也就决定了他们的应用场景,比如在逆波兰表达式的计算中,我们需要用栈来协助完成,而对于计算中资源的管理,我们更多的是借助队列。
在面试中,栈和队列的相互实现也就成为一个考点。比如用俩个栈实现按一个队列,或者用两个队列实现一个栈,这种问题一定要抓住他们的各自特点。
//两个栈实现一个队列
class MyQueue {
public:
stack<int> stack1;
stack<int> stack2;
MyQueue() {
// do intialization if necessary
}
void push(int element) {
// write your code here
stack1.push(element);
}
int pop() {
// write your code here
if(stack1.size()==0)
return 0;
while(stack1.size()!=1)
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
int pop=stack1.top();
stack1.pop();
while(stack2.size()!=0)
{
int top=stack2.top();
stack2.pop();
stack1.push(top);
}
return pop;
}
int top() {
// write your code here
if(stack1.size()==0)
return 0;
while(stack1.size()!=1)
{
int top=stack1.top();
stack1.pop();
stack2.push(top);
}
int ret=stack1.top();
while(stack2.size()!=0)
{
int top=stack2.top();
stack2.pop();
stack1.push(top);
}
return ret;
}
};
在leetcode中有道题是计算逆波兰表达式的值,这道题其实也是应用了栈来实现的。
题目描述
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are+,-,*,/. Each operand may be an integer or another expression.
Some examples:
[“2”, “1”, “+”, “3”, ““] -> ((2 + 1) 3) -> 9
[“4”, “13”, “5”, “/”, “+”] -> (4 + (13 / 5)) -> 6
思路:当我们去读取字符时,如果是数字就直接转换为数字入栈,如果是+-*/然后将栈顶的元素pop出来接着进行相对应的运算。
class Solution {
public:
int evalRPN(vector<string> &tokens) {
stack<int> s;
int len=tokens.size();
if(len==0) return 0;
for(int i=0;i<len;i++)
{
string str=tokens[i];
if(str=="+"||str=="-"||str=="*"||str=="/")
{
if(s.size()<2)
return 0;
int b=s.top();
s.pop();
int a=s.top();
s.pop();
int ret=0;
char op=str[0];
switch(op)
{
case '+':
ret=a+b;
break;
case '-':
ret=a-b;
break;
case '*':
ret=a*b;
break;
case '/':
ret=a/b;
break;
}
s.push(ret);
}
else
{
s.push(stoi(str));
}
}
return s.top();
}
};