一、用两个栈来实现一个队列,完成队列的push和pop操作,队列中的元素为int类型
思路:两个栈实现队列,根据栈先进后出的原则,为了保证队列输出的顺序,必须进行两次入栈的操作。
两种解法大致相同。。。。
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(new Integer(node));//全部放入栈1之中
}
public int pop() {
int pop;
while(!stack1.isEmpty()){
stack2.push(stack1.pop());//将栈1压到栈二当中
}
pop=stack2.pop().intValue();//将栈二的数据全部出栈
while(!stack2.isEmpty()){
stack1.push(stack2.pop());//将栈2压到栈1当中
}
return pop;
}
}
import java.util.Stack;
public class Solution {
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
public void push(int node) {
stack1.push(node);//全部放入栈1之中
}
public int pop() {
if(stack2.isEmpty())
{
while(!stack1.isEmpty())
{
stack2.push(stack1.pop());
}
}
return stack2.pop();
}
}
二、逆波兰数:用逆波兰表示法计算算术表达式的值。有效的运算符+,-,*,/。每个操作数可以是一个整数或另一个表达式。
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
思路:也是借助于入栈出栈的想法,原始数据不停入栈。遇到运算符,两个数据出栈,先出栈的在右边,后出栈的在左边。再将运算结果入栈,直至遍历完所有的数字,直接进行出栈操作,得到最终结果。
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack=new Stack<Integer>();
int a;
int b;
int i=0;
for(;i<tokens.length;i++){
String c=tokens[i];
if(c.equals("+")){
a=stack.pop();
b=stack.pop();
stack.add(b+a);
}
else if(c.equals("-")){
a=stack.pop();
b=stack.pop();
stack.add(b-a);
}
else if(c.equals("*")){
a=stack.pop();
b=stack.pop();
stack.add(b*a);
}
else if(c.equals("/")){
a=stack.pop();
b=stack.pop();
stack.add(b/a);
}
}
return stack.pop();
}
}