栈及相关算法问题
文章目录
- 栈
栈
链表实现栈
private class Node<E> {E value;Node<E> next;public Node(E value, Node<E> next) {this.value = value;this.next = next;}
}
数组实现栈
private E[] array;
private int top=0;
利用栈解决算法问题
力扣-有效的括号
解题思路
import java.util.*;
class Solution {public boolean isValid(String s) {LinkedList<Character> stack=new LinkedList<>();char[] a=s.toCharArray();for(int i=0;i<a.length;i++){if(a[i]=='(')stack.push(')');else if(a[i]=='[')stack.push(']');else if(a[i]=='{')stack.push('}');else{if(stack.isEmpty()||a[i]!=stack.peek())return false;else stack.poll();}}if(stack.isEmpty())return true;return false;}
}
逆波兰表达式的运算值
解题思路
用栈解决
import java.util.*;
class Solution {public int evalRPN(String[] tokens) {LinkedList<Integer> stack=new LinkedList<>();for(int i=0;i<tokens.length;i++){if("+".equals(tokens[i])||"*".equals(tokens[i])||"-".equals(tokens[i])|"/".equals(tokens[i])){int b=stack.poll();int a=stack.poll();int result=choice(tokens[i],a,b);stack.push(result);}else {int a=Integer.parseInt(tokens[i]);stack.push(a);}}if(stack.isEmpty())return 0;return stack.poll();}public static int choice(String c,int a,int b){if("+".equals(c))return a+b;else if("-".equals(c))return a-b;else if("*".equals(c))return a*b;else if("/".equals(c)){if(b==0) return 0;else return a/b;}return 0;}
}
中缀运算转后缀运算
思路
代码实现
String s="a*(b+c)";LinkedList<Character> stack=new LinkedList<>();StringBuffer sb=new StringBuffer();for(int i=0;i<s.length();i++){char c=s.charAt(i);switch (c){case '+','-','*','/':{if(stack.isEmpty())stack.push(c);else{if(priority(c)>priority(stack.peek()))stack.push(c);else {while(!stack.isEmpty()&&priority(c)<=priority(stack.peek()))sb.append(stack.poll());stack.push(c);}}}break;case '(':stack.push(c);break;case ')':{while(!stack.isEmpty()&&stack.peek()!='(') {sb.append(stack.poll());}stack.poll();}break;default:{sb.append(c);}}}while(!stack.isEmpty()){sb.append(stack.poll());}System.out.println(sb);
}
public static int priority(char s)
{switch (s){case '*','/': return 2;case '+','-':return 1;case '(':return 0;}return 0;
}