/// <summary> /// 栈(数组)测试 /// </summary> static void ArrayStackTest() { ArrayStack <int> stack = new ArrayStack <int>(10); Console.WriteLine("01初始化堆栈,当前为空栈"); Console.WriteLine("IsEmpty:{0}", stack.IsEmpty()); Random rand = new Random(); for (int i = 0; i < 10; i++) { stack.Push(rand.Next(1, 10));//随机生成1—10压栈 } Console.WriteLine("02随机压入1-10内10个数据"); Console.WriteLine("IsEmpty:{0}", stack.IsEmpty()); Console.WriteLine("Size:{0}", stack.Size); Console.WriteLine("03弹出栈内10个元素,依次打印他们的值"); for (int i = 0; i < 10; i++) { int node = stack.Pop(); Console.Write(node + " ");//依次打印弹出元素,用“ ”隔开 } Console.WriteLine(); Console.WriteLine("IsEmpty:{0}", stack.IsEmpty()); Console.WriteLine("Size:{0}", stack.Size); }
public int Result() { int result = 0; int lastop = 0; try { char[] c = expression.ToCharArray(); for (int i = 0; i < c.Length; i++) { bool b = int.TryParse(c[i].ToString(), out int m); if (b) { number.Push(m); } else { if (operation.IsEmpty()) { operation.Push(c[i].ToString()); lastop = dict[c[i].ToString()]; } else if (lastop > dict[c[i].ToString()]) { //下面代码有问题不能连乘 int x = number.Pop(); int y = number.Pop(); string op = operation.Pop(); int r = calc(x, y, op); number.Push(r); lastop = dict[c[i].ToString()]; operation.Push(c[i].ToString()); } else { operation.Push(c[i].ToString()); lastop = dict[c[i].ToString()]; } } } while (!operation.IsEmpty()) { int x = number.Pop(); int y = number.Pop(); string op = operation.Pop(); int r = calc(x, y, op); number.Push(r); } } catch (Exception ex) { Console.WriteLine(ex.Message); } result = number.Pop(); Console.WriteLine(result); return(result); }
internal void Run() { ArrayStack numStack = new ArrayStack(10); ArrayStack operStack = new ArrayStack(10); int index = 0;//指针 int num1, num2, oper, res; char ch; string keepNum = ""; while (true) { //扫描每一个字符 ch = expression.Substring(index, 1).ToCharArray()[0]; if (IsOper(ch)) { //判断当前符号栈是否为空 if (!operStack.IsEmpty()) { if (Priority(ch) <= Priority(operStack.Peek())) { //从数栈中pop两个数,从符号栈中pop出一个符号,计算; //将计算结果放入数栈,将当前符号栈如栈 num1 = numStack.Pop(); num2 = numStack.Pop(); oper = operStack.Pop(); res = Calc(num1, num2, oper); numStack.Push(res); operStack.Push(ch); } else { //入栈 operStack.Push(ch); } } else { //为空直接入栈 operStack.Push(ch); } } else { //如果是数字,直接入栈 //numStack.Push(ch-48); //如果是多位数的话,不能直接入栈 keepNum += ch;//先不着急入栈,先存一下 if (index == expression.Length - 1) { //如果ch已经是最后一个了,就不要往后看了 numStack.Push(ch - 48); } else { //继续扫描,往后看一位,直到后面的是运算符,拼接后入栈 if (IsOper(expression.Substring(index + 1, 1).ToCharArray()[0])) { //如果后一位是运算符,入栈 numStack.Push(Convert.ToInt32(keepNum)); keepNum = ""; } } } index++; if (index >= expression.Length) { break; } } //扫描完后,依次弹出计算 while (true) { //如果符号栈为空,数栈中的就是结果 if (operStack.IsEmpty()) { break; } num1 = numStack.Pop(); num2 = numStack.Pop(); oper = operStack.Pop(); res = Calc(num1, num2, oper); numStack.Push(res); } res = numStack.Pop(); Console.WriteLine("计算结果为" + res.ToString()); }