栈 stack
先入后出 FILO-FIRST IN LAST OUT 有序列表
-
限制线性表中的元素的插入和删除只能在线性表的同一端进行。
-
允许插入和删除的一端,为变化的一端,称为栈顶 top,另一端为固定的一端,称为栈底 bottom
-
最先放入栈中的元素在栈底,最后放入的在栈顶
-
删除元素,最后放入的元素最先被删除,最先放入的元素最后被删除
出栈:pop
入栈:push
应用场景
- 子程序的调用
- 处理递归调用
- 表达式的转换(中缀转后缀)
- 二叉树的遍历
- 图形的深度优先搜索 depth - first
栈的实现
- 使用数组来模拟栈
- 定义一个 top 来表示栈顶,初始化为 -1
- 入栈的操作,当有数据加入到栈时,top++;stack[top] = data
- 出栈的操作,int value = stack[top]; top–; return value;
栈的遍历,入栈,出栈
package stack;
import java.util.Scanner;
public class ArrayStackDemo {
public static void main(String[] args) {
ArrayStack stack = new ArrayStack(4);
String key = "";
boolean loop = true; // control whether exit menu
Scanner scanner = new Scanner(System.in);
while(loop){
System.out.println("show: show the stack");
System.out.println("exit: exit");
System.out.println("push: add data into the stack");
System.out.println("pop: get data from stack");
System.out.println("please input order");
key = scanner.next();
switch (key){
case "show":
stack.list();
break;
case "push":
System.out.println("please enter a num");
int value = scanner.nextInt();
stack.push(value);
break;
case "pop":
try {
int res = stack.pop();
System.out.printf("data poped:%d\n",res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case "exit":
scanner.close();
loop = false;
break;
default:
break;
}
}
System.out.println("app stop");
}
}
// define a ArrayStack representing stack
class ArrayStack{
private int maxSize; // size of stack
private int[] stack; // store data
private int top = -1; // stack top
public ArrayStack(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize]; // initialize
}
// stack is full
public boolean isFull(){
return top == maxSize - 1;
}
// stack is empty
public boolean isEmpty(){
return top == -1;
}
// push into stack
public void push(int value){
// is stack full?
if(isFull()){
System.out.println("stack is full");
return;
}
top++;
stack[top] = value;
}
// pop
public int pop(){
// is stack empty?
if(isEmpty()){
// throw exception
throw new RuntimeException("empty stack");
}
int value = stack[top];
top--;
return value;
}
// traversal stack -- from top to end
public void list(){
if(isEmpty()){
System.out.println("no data");
return;
}
for(int i = top;i >= 0;i--){
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
}
栈实现计算器(中缀表达式)
思路分析
数栈 numStack:存放数
符号栈 operStack:存放运算符
-
通过一个 index 值(索引),来遍历我们的表达式
-
如果发现是一个数字,直接入数栈
-
如果扫描到的是符号,分两种情况
- 如果当前符号栈为空,则入栈
- 如果符号栈有操作符,就进行比较,如果当前操作符的优先级小于或等于栈中的操作符,则从数栈中pop出两个数,再从符号栈中pop一个符号,进行运算,将结果再入数栈,把当前的操作符入符号栈;如果当前的操作符的优先级大雨栈中的操作符,就直接入符号栈
-
当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并进行运算
-
最后再数栈中只有一个数组,即为表达式的结果
实现流程
- 数组实现栈:class ArrayStack2{}
- 方法:判断优先级 public int priority(int oper)
- 方法:判断是否为运算符 public boolean isOper(char val)
- 方法:计算结果 public int cal(int num1,int num2,int oper)
- 方法:查看栈顶元素 public int peek()
- main() 方法实现:
- 传入表达式
- 创建数栈和符号栈
- 定义相关变量
- while 循环扫描表达式
- 按照之前的思路分析2,3编程
问题分析
问题:多位数计算错误,当一个数是多位数时,不能按照第一位、第二位的方式将数入栈
The result of 70+2*6-2 is 10
问题定位:numStack.push(ch-48);
问题解决:在处理数时,需要向expression的表达式的index后再看一位,如果是数就继续扫描,如果是符号才入栈;需要定义一个字符串变量用于拼接;注意每次将数入数栈之后,要清空用于拼接的字符串变量
同时也要注意 index 在扫描时,string长度越界的问题
字符串转 int : Integer.parseInt(String)
代码实现
package stack;
public class Calculator {
public static void main(String[] args) {
String expression = "70+2*6-2";
// create 2 stack. one for storing numbers, the other for storing operators
ArrayStack2 numStack = new ArrayStack2(10);
ArrayStack2 operStack = new ArrayStack2(10);
// define variables
int index = 0; // for scanning
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' '; // store char generated by each scan into ch
String keepNum = ""; // for splicing multiple digits
// while loop scan expression
while(true) {
// get each char from expression
ch = expression.substring(index, index + 1).charAt(0);
// determine the type of ch, do next step
if (operStack.isOper(ch)) { // if it is oper
// determine whether current operStack is empty
if (!operStack.isEmpty()) {
// not empty
// determine priority
if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
// pop two numbers from numStack
num1 = numStack.pop();
num2 = numStack.pop();
// pop one oper
oper = operStack.pop();
// calculate
res = numStack.cal(num1, num2, oper);
// push result into numStack
numStack.push(res);
// push current oper into operStack
operStack.push(ch);
} else {
// push into stack
operStack.push(ch);
}
} else {
// if empty, push into operStack
operStack.push(ch);
}
} else {
// if it is number, push into numStack
// numStack.push(ch-48); // '1' -- 1
keepNum += ch;
// if ch is the last digit of expression, push into stack
if(index == expression.length()-1){
numStack.push(Integer.parseInt(keepNum));
}else{
// determine if next char is num, if it is, continue scan
// if it is oper, push into numStack
if(operStack.isOper(expression.substring(index+1,index+2).charAt(0))){
// if next digit isOper
numStack.push(Integer.parseInt(keepNum));
// !!! clear keepNum
keepNum = "";
}
}
}
// index + 1, determine whether scan to the end of expression
index++;
if(index >= expression.length()){
break;
}
}
// when scanned all expression, pop number and oper from
// numStack and operStack by order, and do calculation
while(true){
// if operStack is empty, finish, only one num left in numStack
if(operStack.isEmpty()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1,num2,oper);
numStack.push(res);
}
System.out.printf("The result of %s is %d ",expression,numStack.pop());
}
}
class ArrayStack2{
private int maxSize; // size of stack
private int[] stack; // store data
private int top = -1; // stack top
public ArrayStack2(int maxSize) {
this.maxSize = maxSize;
stack = new int[this.maxSize]; // initialize
}
// look top value of stack, not pop
public int peek(){
return stack[top];
}
// stack is full
public boolean isFull(){
return top == maxSize - 1;
}
// stack is empty
public boolean isEmpty(){
return top == -1;
}
// push into stack
public void push(int value){
// is stack full?
if(isFull()){
System.out.println("stack is full");
return;
}
top++;
stack[top] = value;
}
// pop
public int pop(){
// is stack empty?
if(isEmpty()){
// throw exception
throw new RuntimeException("empty stack");
}
int value = stack[top];
top--;
return value;
}
// traversal stack -- from top to end
public void list(){
if(isEmpty()){
System.out.println("no data");
return;
}
for(int i = top;i >= 0;i--){
System.out.printf("stack[%d]=%d\n",i,stack[i]);
}
}
// return priority of operator defined by coder
// use number to indicate priority
// the larger number, the higher priority
public int priority(int oper){
if(oper == '*'||oper == '/'){
return 1;
}else if(oper == '+' || oper == '-'){
return 0;
}else{
return -1;
}
}
// if it is oper?
public boolean isOper(char val){
return val == '+' || val == '-' || val == '*' || val == '/';
}
// calculate
public int cal(int num1,int num2,int oper){
int res = 0;
switch (oper){
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default: break;
}
return res;
}
}