public void PUSH(int data) { dataStack.PUSH(data); if (minimumStack.IsEmpty()) { minimumStack.PUSH(data); } else { minimumStack.PUSH(data < minimumStack.PEEK() ? data : minimumStack.PEEK()); } }
/// <summary> /// Complexity of this code is O(N) /// </summary> /// <param name="expression"></param> /// <returns></returns> public static bool HasMatchingParans(string expression) { try { Stack.Stack <char> openPanransFound = new Stack.Stack <char>(); foreach (char expressionChar in expression) { if (openParans.Contains(expressionChar)) { openPanransFound.PUSH(expressionChar); } if (matchingOpens.ContainsKey(expressionChar)) { if (openPanransFound.GetSize() == 0) { return(false); } if (!matchingOpens.TryGetValue(expressionChar, out char openForTheCloseFound) || !openPanransFound.POP().Equals(openForTheCloseFound)) { return(false); } } } return(openPanransFound.IsEmpty()); } catch (Stack.StackOverflowException ex) { Console.WriteLine(ex); } catch (Stack.StackUnderflowException ex) { Console.WriteLine(ex); } return(false); }
public PostFix ToPostFix() { List <char> operatorsList = new List <char>() { '+', '-', '*', '/' }; List <char> additiveOp = new List <char>() { '+', '-' }; List <char> multiplicativeOp = new List <char>() { '*', '/' }; string returnString = ""; foreach (char input in Expression) //7 { if (input > 96 && input < 123) //2 { _queue.EnQueue(input); continue; } if (input == '(') //3 { _stack.Push(input); continue; } if (input == ')') //4 { while ((char)_stack.Peek() != '(') { _queue.EnQueue(_stack.Pop()); } _stack.Pop(); continue; } if (operatorsList.Contains(input) && (_stack.GetSize() == 0 || (char)_stack.Peek() == '(')) //5 { _stack.Push(input); continue; } while (!_stack.IsEmpty() && (additiveOp.Contains(input) && multiplicativeOp.Contains((char)_stack.Peek()))) //6 { if (operatorsList.Contains(input) && !_stack.IsEmpty()) { if (additiveOp.Contains(input) && multiplicativeOp.Contains((char)_stack.Peek())) { _queue.EnQueue(_stack.Pop()); } else { _stack.Push(input); } } } } while (!_stack.IsEmpty()) { _queue.EnQueue(_stack.Pop()); } while (!_queue.IsEmpty()) { returnString += _queue.DeQueue(); } return(new PostFix(returnString)); }