数据结构与算法day09-栈的应用场景和介绍

栈的一个实际需求:
	请输入一个表达式
	计算式:[7 * 2 * 2 - 5 + 1 - 5 + 3 -3] 点击按钮即可计算值
	请问计算机底层是如何运算得到结果的?注意不是简单的把算式列出运算,
	因为我们看这个算式7 * 2 * 2 - 5,但是计算机怎么理解这个算式(对计算机而言,他
	接收到的就是一个字符串,我们讨论的就是这个问题----栈)


栈的介绍:
	1.栈的英文为stack
	2.栈是一个先入后出(FILO-First in Last Out)的有序列表
	3.栈(stack)是限制线性表中元素的插入和删除只能在线性表的同一端进行的
	一种特殊线性表。允许插入和删除的一端,为变化的一端,称为栈顶(Top),
	另一端为固定的一端,称为栈底(Bottom)
	4.根据栈的定义可知,最先放入栈中元素在栈底,最后放入的元素在栈顶,
	而删除元素刚好相反,最后放入的元素最先删除,最先放入的元素最后删除。

出栈pop与入栈push的概念图如下:
在这里插入图片描述

栈的应用场景:
	1.子程序的调用:在跳往子程序前,会先将下个指令的地址存到堆栈
	中,直到子程序执行完后再将地址取出,以回到原来的程序中。
	2.处理递归调用:和子程序的调用类似,只是出了存储下一个指令的
	地址外,也将参数、区域变量等数据存入栈中。
	3.表达式的转换[中缀表达式转后缀表达式]与求值(实际解决)。[后续会讲解]
	4.二叉树的遍历。[后续会讲解]
	5.图形的深度优先(depth-first)搜索法。[后续会讲解]

栈的快速入门:
	1.用数组模拟栈的使用,由于栈是一种有序列表,当然可以使用数组的结构来存储
	栈的数据内容,下面我们就用数组模拟栈的出栈,入栈等操作。
	2.实现思路分析,并画出示意图:
		1.使用数组模拟栈
		2.定义一top来表示栈顶初始化为-1
		3.入栈的操作,当有数据加入到栈的时,top++; stack[top] = data;
		4.出栈的操作,int value = stack[top]; top-- , return  value;
	3.课后作业:使用链表实现栈

在这里插入图片描述

数组模拟栈的代码如下:

public class ArrayStackDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		ArrayStack stack = new ArrayStack(4);
		String key = "";
		boolean loop = true;
		Scanner sc = new Scanner(System.in);
		
		while (loop) {
			System.out.println("show:显示栈");
			System.out.println("exit:退出程序");
			System.out.println("push:数据入栈");
			System.out.println("pop:数据出栈");
			
			System.out.println("请输入你的选择:");
			key = sc.next();
			switch (key) {
			case "show":
				stack.list();
				break;
			case "push":
				System.out.println("请输入一个数:");
				int value = sc.nextInt();
				stack.push(value);
				break;
			case "pop":
				try {
					int res = stack.pop();
					System.out.printf("出栈的数据是%d\n", res);
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				break;
			case "exit":
				sc.close();
				loop = false;
				System.out.println("程序退出~");
				break;
			default:
				break;
			}
		}
	}
}

// 用数组模拟栈
class ArrayStack {
	// 栈的容量
	private int maxSize;
	// 数组模拟栈,数据放在该数组中
	private int[] stack;
	// 表示栈顶,初始化为-1
	private int top = -1;

	public ArrayStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[maxSize];
	}
	
	// 栈满判断
	public boolean isFull() {
		return top == maxSize - 1;
	}
	
	// 栈空判断
	public boolean isEmpty() {
		return top == -1;
	}
	
	// 入栈
	public void push(int value) {
		// 先判断栈是否满
		if (isFull()) {
			System.out.println("栈满~");
			return;
		}
		top++;
		stack[top] = value;
	}
	
	// 出栈
	public int pop() {
		// 先判断栈是否空
		if (isEmpty()) {
			// 抛出非检查异常,不需要捕获
			// 为什么需要抛出异常,因为抛出异常就不用return
			throw new RuntimeException("栈空,没有数据~");
		}
		int value = stack[top];
		top--;
		return value;
	}
	
	// 遍历栈,遍历时,需要从栈顶开始显示数据
	public void list() {
		if (isEmpty()) {
			// 为什么没有抛出异常,因为不用返回数据
			System.out.println("栈空~");
			return;
		}
		// 需要从栈顶开始显示数据
		for (int i = top; i >= 0; i--) {
			System.out.printf("stack[%d] = %d\n", i, stack[i]);
		}
	}
}

补充-单向链表实现栈代码如下:

public class LinkedListStackDemo {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Node node1 = new Node(1);
		Node node2 = new Node(2);
		Node node3 = new Node(3);
		Node node4 = new Node(4);
		LinkedListStack linkedListStack = new LinkedListStack();
		
		System.out.println();
		System.out.println("数据压栈~");
		linkedListStack.push(node2);
		linkedListStack.push(node3);
		linkedListStack.push(node1);
		linkedListStack.push(node4);
		
		System.out.println();
		System.out.println("栈数据显示~");
		linkedListStack.stackPrint();
		
		System.out.println();
		System.out.println("数据出栈~");
		linkedListStack.pop();
		linkedListStack.pop();
		linkedListStack.pop();
		linkedListStack.pop();
		
		System.out.println();
		System.out.println("栈数据显示~");
		linkedListStack.stackPrint();
	}

}

// 使用链表模拟栈的思路
// 当入栈时,找到链表的最后一个,然后将数据添加到末尾
// 当出栈时,找到链表的最后一个节点的前一个 ,然后将该节点指向空,则最后一个节点将删除
// 遍历栈的方法和反向遍历单链表的方式一致
class LinkedListStack {
	// 头结点,不算在栈数据中
	private Node head = new Node(0);
	
	public void push(Node node) {
		// 判断是否为空栈
		if (head.getNext() == null) {
			head.setNext(node);
			System.out.println("压栈数据是:" + node.getNo());
			return;
		}
		Node cur = head;
		while (true) {
			if (cur.getNext() == null) {// 栈顶
				System.out.println("压栈数据是:" + node.getNo());
				cur.setNext(node);
				break;
			}
			cur = cur.getNext();
		}
	}
	
	public void pop() {
		Node temp = head;
		// 判断是否为空栈
		if (temp.getNext() == null) {
			System.out.println("栈为空,无法获取数据~");
			return;
		}
		while (true) {
			if (temp.getNext().getNext() == null) {// 检测是否到栈顶末尾
				System.out.println("出栈数字是:" + temp.getNext().getNo());
				temp.setNext(null);
				break;
			}
			temp = temp.getNext();
		}
	}
	
	public void stackPrint() {
		// 判断是否为空
		if (head.getNext() == null) {
			System.out.println("栈为空~");
			return;
		}
		Node temp = head;
		Stack<Node> stack = new Stack<Node>();
		// 遍历
		while (true) {
			// 判断是否到链表末尾
			if (temp.getNext() == null) {
				break;
			}
			Node node = temp.getNext();
			stack.push(node);
			temp = temp.getNext();
		}
		
		System.out.println("栈大小:" + stack.size());
		int size = stack.size();
		for (int i = 0; i < size; i++) {
			System.out.println("栈的数据:" + stack.pop().getNo());
		}
	}
	
}

class Node {
	private int no;
	private Node next;
	
	public Node(int no) {
		this.no = no;
	}

	public int getNo() {
		return no;
	}

	public void setNo(int no) {
		this.no = no;
	}

	public Node getNext(){
			return next;
		}

	public void setNext(Node next) {
		this.next = next;
	}
}

栈实现综合计算器

使用栈来实现综合计算器-自定义优先级[priority]
请输入一个表达式
计算式:[7*2*2-5+1-5+3+3]点击计算

简化思路得到思路:

第一步 3+2*6-2
第二步 7*2*2-5+1-5+3-4

在这里插入图片描述

代码如下:缺点是只可以计算一位数

public class Calculator {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 根据前面思路,完成中缀表达式的运算
		// 缺点无法运行一位以上
		String expression = "7+2*6-4";
		// 创建2个栈,树栈,一个符号栈
		CalculatorStack numStack = new CalculatorStack(10);
		CalculatorStack operStack = new CalculatorStack(10);
		// 定义需要的相关变量
		int index = 0; // 用于扫描字符串
		
		int num1 = 0;
		int num2 = 0;
		int oper = 0;
		int res = 0;
		char ch = ' '; // 将每次扫描得到char保存到ch中
		
		// 开始while循环的扫描expression
		// 注意if / else if / else的用法
		while (true) {
			// 依次得到expression中的每一个字符
			ch = expression.substring(index, index+1).charAt(0);
			// 判断ch是什么,然后做什么相应的处理
			if (operStack.isOper(ch)) {
				// 判断当前的符号栈是否为空
				if (!operStack.isEmpty()) {
					// 如果符号栈有操作符,就进行比较,
					// 如果当前的操作符的优先级小于或等于栈中的操作符
					// 在符号栈中pop出一个符号,进行运算,将得到结果
					// 入数栈,然后将当前的操作符入符号栈
					if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
						num1 = numStack.pop();
						num2 = numStack.pop();
						oper = operStack.pop();
						res = numStack.cal(num1, num2, oper);
						// 把运算后的结果入数栈
						numStack.push(res);
						// 然后将当前扫描的操作符入栈
						operStack.push(ch);
					} else {
						// 如果当前的操作符的优先级大于栈中的操作符
						// 就直接入符号栈
						operStack.push(ch);
					}
				} else {
					// 如果为空直接入栈
					operStack.push(ch);
				}
			} else {
				// 如果是数,直接入数栈
				// 字符与实际数字相差48
				// 因为初始字符0 是 48
				// 注意点
				numStack.push(ch - 48);
			}
			// 让index + 1, 并判断是否扫描到expression最后
			index++;
			if (index >= expression.length()) {
				break;
			}
		}
		
		// 当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运行
		while (true) {
			// 如果符号栈为空,则计算到最后的结果,数栈中只有一个数字【结果】
			if (operStack.isEmpty()) {
				break;
			}
			num1 = numStack.pop();
			num2 = numStack.pop();
			oper = operStack.pop();
			res = numStack.cal(num1, num2, oper);
			numStack.push(res); // 入栈
		}
		// 将数栈的最后书,pop出,就是结果
		int res2 = numStack.pop();
		System.out.printf("表达式 %s = %d", expression, res2);
	}

}

// 用数组模拟栈
class CalculatorStack {
	// 栈的容量
	private int maxSize;
	// 数组模拟栈,数据放在该数组中
	private int[] stack;
	// 表示栈顶,初始化为-1
	private int top = -1;

	public CalculatorStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[maxSize];
	}
	
	// 增加一个方法,可以返回当前栈顶的值,但是不是真正的pop,因为指针没有变化
	public int peek() {
		return stack[top];
	}
	
	// 栈满判断
	public boolean isFull() {
		return top == maxSize - 1;
	}
	
	// 栈空判断
	public boolean isEmpty() {
		return top == -1;
	}
	
	// 入栈
	public void push(int value) {
		// 先判断栈是否满
		if (isFull()) {
			System.out.println("栈满~");
			return;
		}
		top++;
		stack[top] = value;
	}
	
	// 出栈
	public int pop() {
		// 先判断栈是否空
		if (isEmpty()) {
			// 抛出非检查异常,不需要捕获
			// 为什么需要抛出异常,因为抛出异常就不用return
			throw new RuntimeException("栈空,没有数据~");
		}
		int value = stack[top];
		top--;
		return value;
	}
	
	// 遍历栈,遍历时,需要从栈顶开始显示数据
	public void list() {
		if (isEmpty()) {
			// 为什么没有抛出异常,因为不用返回数据
			System.out.println("栈空~");
			return;
		}
		// 需要从栈顶开始显示数据
		for (int i = top; i >= 0; i--) {
			System.out.printf("stack[%d] = %d\n", i, stack[i]);
		}
	}
	
	// 返回运算符的优先级,优先级是程序员定的,优先级使用数字表示,
	// 数字越大,则优先级越高
	public int priority(int oper) {
		// 字符的本质也是数字,所以字符可以当数字使用
		if (oper == '*' || oper == '/') {
			return 1;
		} else if (oper == '+' || oper == '-') {
			return 0;
		} else {
			// 假定目前的表达式只有 + - * /
			return -1; 
		}
	}
	
	// 判断是不是一个运算符
	public boolean isOper(char val) {
		return val == '+' || val == '-' || val == '*' || val == '/';
	}
	
	// 计算方法
	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;
	}
}

计算多位数的计算器,代码如下:

public class Calculator {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		// 根据前面思路,完成中缀表达式的运算
		// 缺点无法运行一位以上
		String expression = "10+20+6/3-1";
		// 创建2个栈,树栈,一个符号栈
		CalculatorStack numStack = new CalculatorStack(10);
		CalculatorStack operStack = new CalculatorStack(10);
		// 定义需要的相关变量
		int index = 0; // 用于扫描字符串
		
		int num1 = 0;
		int num2 = 0;
		int oper = 0;
		int res = 0;
		char ch = ' '; // 将每次扫描得到char保存到ch中
		String keepNum = ""; // 用于拼接多位数
		
		// 开始while循环的扫描expression
		while (true) {
			// 依次得到expression中的每一个字符
			ch = expression.substring(index, index+1).charAt(0);
			// 判断ch是什么,然后做什么相应的处理
			if (operStack.isOper(ch)) {
				// 判断当前的符号栈是否为空
				if (!operStack.isEmpty()) {
					// 如果符号栈有操作符,就进行比较,
					// 如果当前的操作符的优先级小于或等于栈中的操作符
					// 在符号栈中pop出一个符号,进行运算,将得到结果
					// 入数栈,然后将当前的操作符入符号栈
					if (operStack.priority(ch) <= operStack.priority(operStack.peek())) {
						num1 = numStack.pop();
						num2 = numStack.pop();
						oper = operStack.pop();
						res = numStack.cal(num1, num2, oper);
						// 把运算后的结果入数栈
						numStack.push(res);
						// 然后将当前扫描的操作符入栈
						operStack.push(ch);
					} else {
						// 如果当前的操作符的优先级大于栈中的操作符
						// 就直接入符号栈
						operStack.push(ch);
					}
				} else {
					// 如果为空直接入栈
					operStack.push(ch);
				}
			} else {
				// 如果是数,直接入数栈
				// 字符与实际数字相差48
				// 因为初始字符0 是 48
//				numStack.push(ch - 48);
				
				// 改良入栈,使得多位数也可以计算
				// 分析思路
				// 1.当处理多位数时,不能发现是一个数就立即入栈,因为他可能是多位数
				// 2.在处理数,需要向expression的表达式的index后再看一位,如果是数栈就进行扫描,如果是符号才停止扫描并入栈
				// 3.因此我们需要定义一个变量字符串,用于拼接
				
				// 处理多位数
				keepNum += ch;
				
				// 如果ch已经是expression的最后一位直接入栈
				if (index == expression.length()-1) {
					numStack.push(Integer.parseInt(keepNum));
				}
				
				// 判断下一个字符是不是数字,如果是数字,则继续扫描
				// 如果是运算符,则将数字入栈
				// 注意是看后一位,不是index++,因为此处没有index赋值操作
				else if (operStack.isOper(expression.substring(index+1, index+2).charAt(0))) {
					// 是操作符,则直接将数字入栈
					// keepNum是字符串需要转成int
					numStack.push(Integer.parseInt(keepNum));
					// 清空全局的keepNum
					keepNum = "";
				}
			}
			// 让index + 1, 并判断是否扫描到expression最后
			index++;
			if (index >= expression.length()) {
				break;
			}
		}
		
		// 当表达式扫描完毕,就顺序的从数栈和符号栈中pop出相应的数和符号,并运行
		while (true) {
			// 如果符号栈为空,则计算到最后的结果,数栈中只有一个数字【结果】
			if (operStack.isEmpty()) {
				break;
			}
			num1 = numStack.pop();
			num2 = numStack.pop();
			oper = operStack.pop();
			res = numStack.cal(num1, num2, oper);
			numStack.push(res); // 入栈
		}
		// 将数栈的最后书,pop出,就是结果
		int res2 = numStack.pop();
		System.out.printf("表达式 %s = %d", expression, res2);
	}

}

// 用数组模拟栈
class CalculatorStack {
	// 栈的容量
	private int maxSize;
	// 数组模拟栈,数据放在该数组中
	private int[] stack;
	// 表示栈顶,初始化为-1
	private int top = -1;

	// 
	public CalculatorStack(int maxSize) {
		this.maxSize = maxSize;
		stack = new int[maxSize];
	}
	
	// 增加一个方法,可以返回当前栈顶的值,但是不是真正的pop,因为指针没有变化
	public int peek() {
		return stack[top];
	}
	
	// 栈满判断
	public boolean isFull() {
		return top == maxSize - 1;
	}
	
	// 栈空判断
	public boolean isEmpty() {
		return top == -1;
	}
	
	// 入栈
	public void push(int value) {
		// 先判断栈是否满
		if (isFull()) {
			System.out.println("栈满~");
			return;
		}
		top++;
		stack[top] = value;
	}
	
	// 出栈
	public int pop() {
		// 先判断栈是否空
		if (isEmpty()) {
			// 抛出非检查异常,不需要捕获
			// 为什么需要抛出异常,因为抛出异常就不用return
			throw new RuntimeException("栈空,没有数据~");
		}
		int value = stack[top];
		top--;
		return value;
	}
	
	// 遍历栈,遍历时,需要从栈顶开始显示数据
	public void list() {
		if (isEmpty()) {
			// 为什么没有抛出异常,因为不用返回数据
			System.out.println("栈空~");
			return;
		}
		// 需要从栈顶开始显示数据
		for (int i = top; i >= 0; i--) {
			System.out.printf("stack[%d] = %d\n", i, stack[i]);
		}
	}
	
	// 返回运算符的优先级,优先级是程序员定的,优先级使用数字表示,
	// 数字越大,则优先级越高
	public int priority(int oper) {
		// 字符的本质也是数字,所以字符可以当数字使用
		if (oper == '*' || oper == '/') {
			return 1;
		} else if (oper == '+' || oper == '-') {
			return 0;
		} else {
			// 假定目前的表达式只有 + - * /
			return -1; 
		}
	}
	
	// 判断是不是一个运算符
	public boolean isOper(char val) {
		return val == '+' || val == '-' || val == '*' || val == '/';
	}
	
	// 计算方法
	// 
	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;
	}
}

完善添加小括号功能代码:

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值