数据结构:后缀表达式(逆波兰表达式)
生活随笔
收集整理的這篇文章主要介紹了
数据结构:后缀表达式(逆波兰表达式)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?逆波蘭表達式計算
package com.atchina.stack;import java.util.ArrayList; import java.util.List; import java.util.Stack;public class PolandNotation {public static void main(String[] args) {//先定義一個逆波蘭表達式String suffixExpression = "3 4 + 5 * 6 - ";// 思路// 1 先將"3 4 + 5 x 6 - "放到arraylist中List<String> rpnList = getListString(suffixExpression);System.out.println(rpnList);int res = calculate(rpnList);System.out.println(res);System.out.println("hello world");}// 將一個逆波蘭表達式,依次將數據和運算符放入到ArrayList中public static List<String> getListString(String suffixExpression){String[] split = suffixExpression.split(" ");List<String> list = new ArrayList<String>();for(String ele : split){list.add(ele);}return list;}// 完成對逆波蘭表達式的運算public static int calculate(List<String> ls) {// 創(chuàng)建一個棧區(qū),只需要一個棧即可Stack<String> stack = new Stack<String>();// 遍歷ls "3 4 + 5 * 6 - "for (String item : ls) {// 這里使用正則表達式來取出數if (item.matches("\\d+")) {// 入棧stack.push(item);} else {// pop 兩個書,并運算,再將結果入棧int num2 = Integer.parseInt(stack.pop());int num1 = Integer.parseInt(stack.pop());int res = 0;if (item.equals("+")) {res = num1 + num2;} else if (item.equals("-")) {res = num1 - num2;} else if (item.equals("*")) {res = num1 * num2;} else if (item.equals("/")) {res = num1 / num2;} else {throw new RuntimeException("運算符有誤");}// 把res入棧stack.push(res + "");}}return Integer.parseInt(stack.pop());} }?
中綴表達式轉后綴表達式的思路步驟分析
?
《新程序員》:云原生和全面數字化實踐50位技術專家共同創(chuàng)作,文字、視頻、音頻交互閱讀總結
以上是生活随笔為你收集整理的数据结构:后缀表达式(逆波兰表达式)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: springmvc三十二:spring
- 下一篇: 分布式编程