典型应用:浏览器前进和后退功能
特定的数据结构是对特定场景的抽象。
某个数据集只涉及在一端插入和删除,并后进先出,就该选栈。
如何实现栈
- 顺序栈
- 链式栈
public class ArrayStack{
private String[] items;
private int count;
private int n;
public ArrayStack(int n){
this.items= new String[n];
this.n=n;
this.count=0;
}
public boolean push(String item){
if (count == n) {
return false;
}
items[count]=item;
this.count++;
return true;
}
public String pop(){
if (this.count==0) {
return null;
}
count--;
return items[count];
}
}
链表实现栈
public class LinkedListStack{
private Node top=null;
public void push(String s){
Node newNode=new Node(s,null);
if (top == null) {
top=newNode;
}else{
newNode.next=top;
top=newNode;
}
}
public String pop(){
if (top == null) {
return null;
}
String ans=top.getData();
top=top.next;
return ans;
}
public void printAll(){
Node p=top;
while(p!=null){
System.out.println(p.data+" ");
p=p.next;
}
System.out.println();
}
private static class Node{
private String data;
public Nodel next;
public Node(String data,Node next){
this.data=data;
this.next=next;
}
public String getData(){
return data;
}
}
}
应用
1. 函数调用
2. 表达式求值
import java.util.*;
class Solution {
public int calculate(String s) {
Stack<Integer> nums=new Stack<Integer>();
Stack<Character> symbol=new Stack<Character>();
int num=0;
for (int i = 0; i < s.length(); i++) {
char c=s.charAt(i);
if(c>='0' && c<='9'){
num=num*10+(c-'0');
continue;
}
if (c=='+'||c=='-'||c=='*'||c=='/') {
nums.push(num);
num=0;
}
if(c == ' '){
continue;
}
if(symbol.empty() || grade(symbol.peek())<grade(c)){
symbol.push(c);
// num=0;
continue;
}
while(!symbol.empty() &&grade(symbol.peek())>=grade(c)){
int b=nums.pop();
int a=nums.pop();
nums.push(cal(a,b,symbol.pop()));
}
symbol.push(c);
// num=0;
}
nums.push(num);
while(!symbol.empty()){
int b=nums.pop();
int a=nums.pop();
nums.push(cal(a,b,symbol.pop()));
}
return nums.pop();
}
private int grade(char c){
switch(c){
case '+':
case '-':
return 0;
case '*':
case '/':
return 1;
}
return -1;
}
public int cal(int a,int b,char c) {
System.out.println(a+" "+c+" "+b);
switch(c){
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
return 1<<30;
}
// return 0;
}
public static void main(String[] args) {
String s="1*2-3/4+5*6-7*8+9/10";
Solution solution=new Solution();
System.out.println(solution.calculate(s));
}
}