旅游电子商务网站建设费用百度手机助手app下载
集合类型(Collection)下篇_xml collection-CSDN博客
以上是堆栈的简单介绍,下方是堆栈的使用
题目:给定一个逆波兰表达式(后缀表达式)的字符串数组tokens
,其中每个元素是一个操作数(数字)或者操作符(+
、-
、*
、/
)。使用Stack<double>
来计算表达式的值。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace 逆波兰表达式
{internal class Program{static void Main(string[] args){string[] tokens = { "3", "7", "+", "6", "*" };Console.WriteLine(EvaluatePostfix(tokens));}static double EvaluatePostfix(string[]tokens){Stack<double> stack = new Stack<double>();foreach (string token in tokens){if(double.TryParse(token,out double num)){stack.Push(num);}else{double operand2 = stack.Pop();double operand1 = stack.Pop();switch (token){case "+":stack.Push(operand1 + operand2);break;case "-":stack.Push(operand1 - operand2);break;case "*":stack.Push(operand1 * operand2);break;case "/":stack.Push(operand1 / operand2);break;}}}return stack.Pop();}}
}