public static void TestStack() { try { new GenStack <int>(-500); } catch (ArgumentOutOfRangeException) { Console.WriteLine("Hooray, couldn't create a negative sized stack"); } var myStack = new GenStack <int>(3); try { myStack.Pop(); } catch (InvalidOperationException) { Console.WriteLine("Hooray, it was empty and failed. :-)"); } myStack.Push(1); myStack.Push(2); var popped = myStack.Pop(); if (popped == 2) { Console.WriteLine("Yuhu... Found the value I pushed! :-D "); } myStack.Push(0); myStack.Push(3); myStack.Push(4); myStack.Push(5); Console.WriteLine(myStack.Peek()); //myStack.Pop(); myStack.Pop(); myStack.Pop(); //Console.WriteLine(String.Format("My final write: pop={0}, size={1}", myStack.Pop(), myStack.StackSize)); for (int i = myStack.Count; i > 0; i--) { Console.WriteLine(i + " : " + myStack.Pop()); } }
internal static string Convert(string infix) { string _postfix = ""; string operators = "*/+-"; var _stack = new GenStack <string>(); //var tokens = infix.ToCharArray(); // Breaks with numbers >1 digit var tokens = infix.Split(); foreach (var c in tokens) { //if (Char.IsLetterOrDigit(c) || c == ' ') // previously _operandSet.Contains(c) //if (Char.IsLetterOrDigit(c)) // don't want whitespace? //{ _postfix += c; } if (Regex.IsMatch(c, @"(\w+)")) { _postfix += c + " "; } if (c == "(") { _stack.Push(c); } else if (c == ")") { while (_stack.Peek() != "(") { _postfix += _stack.Pop() + " "; } // append operators to string until '(' _stack.Pop(); // discard '(' } else if (operators.Contains(c)) { if (_stack.Count == 0) { _stack.Push(c); } else { while (_stack.Peek() != "(") // traverse stack until '(' { if (Precedence(c, _stack.Peek())) // if precedence >= then pop ... { _postfix += _stack.Pop() + " "; } else { break; } // ... else break if (_stack.Count == 0) // stack empty - break { break; } } _stack.Push(c); } } //else //{ // _postfix += c; //TODO 1: moving this to here has messed up flow, needs to go back up, probably use regex //} // else throw exception here ? } for (int i = 0; i < _stack.Count; i++) { _postfix += _stack.Pop() + " "; //TODO 2: Then += " " here and Trim() later } _postfix.TrimEnd(); //_postfix = String.Join(" ", _postfix.ToCharArray()); // to space _postfix TODO: But F***s Up e.g. 100 return(_postfix); }
/// <summary> /// Constructor for calculator. /// </summary> /// <param name="stack"> Stack, which we will use.</param> public Calculator(GenStack stack) { this.stack = stack; }