public void Sample() { UInt32 stackCapacity = 1; IStack <SequentialNode <String> > stack = new SequentialStack <String>(stackCapacity); Int32 cycleNumber = 10; Int32 popNumber = cycleNumber / 2; SequentialNode <String> tmpSequentialNode = null; for (Int32 i = 0; i < cycleNumber; i++) { stack.Push(new SequentialNode <String>() { Data = i.ToString() }); if (i >= popNumber) { stack.Pop(); } else { tmpSequentialNode = stack.Get(); Console.WriteLine($"SequentialNode data is 【{tmpSequentialNode.Data}】"); } } Console.WriteLine($"【{MethodBase.GetCurrentMethod().DeclaringType.FullName}】 end."); }
private Int32 GetValueFromPostfixExpression(String postfixExpression) { IStack <SequentialNode <Int32> > stack = new SequentialStack <Int32>(); Int32 length = postfixExpression.Length; StringBuilder sbElement = new StringBuilder(); for (Int32 i = 0; i < length; i++) { Char tmpCharExpression = postfixExpression[i]; //方法一(当前实现) //判断是否是操作数之间的分隔符,如果是则将之前的字符串认为是一个操作数(例如:110) //方法二 //也可以通过栈中的元素*10,相加之和再入栈 if (m_split.Equals(tmpCharExpression)) { if (!String.IsNullOrWhiteSpace(sbElement.ToString())) { stack.Push( new SequentialNode <Int32>() { Data = Int32.Parse(sbElement.ToString()) } ); sbElement = new StringBuilder(); } continue; } //当出现运算符时,弹出栈里面的数字进行运算 if (Char.IsNumber(tmpCharExpression)) { sbElement.Append(tmpCharExpression.ToString()); } else if (stack.Count > 0) { SequentialNode <Int32> node1 = stack.Pop(); SequentialNode <Int32> node2 = stack.Pop(); Int32 result = 0; switch (tmpCharExpression) { case '+': result = node2.Data + node1.Data; break; case '-': result = node2.Data - node1.Data; break; case '*': result = node2.Data * node1.Data; break; case '/': if (0 == node1.Data) { throw new Exception("Zero cannot be used as a divisor."); } result = node2.Data / node1.Data; break; } stack.Push(new SequentialNode <Int32>() { Data = result }); } } return(stack.Pop().Data); }