// Create a stack of integers Stackstack = new Stack (); // Push some elements onto the stack stack.Push(5); stack.Push(10); stack.Push(15); // Peek at the top element of the stack int topElement = stack.Peek(); Console.WriteLine("Top element of the stack is " + topElement); // Pop elements from the stack until it is empty while (stack.Count > 0) { int poppedElement = stack.Pop(); Console.WriteLine("Popped element from the stack is " + poppedElement); }
// Check if a string of parentheses is balanced public static bool IsBalanced(string input) { StackThis code uses a Stack to check if a string of parentheses is balanced. The method `IsBalanced` takes a string input and checks if it has an equal number of opening and closing parentheses. It does this by iterating over each character in the string, pushing onto the stack when it encounters an opening parentheses and popping from the stack when it encounters a closing parentheses. If the stack is empty when encountering a closing parentheses or if the stack is non-empty after iterating over the entire string, the method returns false. Otherwise, it returns true. Package Library: System.Collections.Genericstack = new Stack (); foreach (char c in input) { if (c == '(') { stack.Push(c); } else if (c == ')') { if (stack.Count == 0) { return false; } stack.Pop(); } } return stack.Count == 0; }