Java实现
## 用两个栈实现队列 题目描述 用两个栈来实现一个队列,完成队列的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(node);
}
public int pop() {
if(stack2.size() <= 0){
while(stack1.size() != 0)
stack2.push(stack1.pop());
}
return stack2.pop();
}
}
表达式求值
题目描述
请写一个整数计算器,支持加减乘三种运算和括号。
示例1
输入:“1+2”
返回值:3
示例2
输入:"(2*(3-4))*5"
返回值:-10
示例3
输入:“3+234-1”
返回值:26
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 返回表达式的值
* @param s string字符串 待计算的表达式
* @return int整型
*/
public int solve (String s) {
// write code here
Stack<Integer> stack = new Stack<>();
//结果
int sum = 0;
//默认数字,运算符
int number = 0;
//默认的第一个数字前的运算符为+
char sign = '+';
char[] arr = s.toCharArray();
int n = s.length();
for(int i = 0; i < n; i++){
char c = arr[i];
//是否为左括号
if(c == '('){
int j = i + 1;
int counterPar = 1;
while(counterPar > 0){
if(arr[j] == '(')
counterPar++;
if(arr[j] == ')')
counterPar--;
j++;
}
//运用递归计算括号中的表达式
number = solve(s.substring(i+1, j-1));
i = j - 1;
}
if(Character.isDigit(c)){
number = number * 10 + c - '0';
}
if(!Character.isDigit(c) || i == n - 1){
if(sign == '+')
stack.push(number);
else if(sign == '-')
stack.push(-1 * number);
else if(sign == '*')
stack.push(stack.pop() * number);
else if(sign == '/')
stack.push(stack.pop() / number);
number = 0;
sign = c;
}
}
while(!stack.isEmpty())
sum += stack.pop();
return sum;
}
}