Skip to content

Commit 610a77d

Browse files
Added StackUtils.cs - This utility provides commonly used operations related to stacks
1 parent cf19352 commit 610a77d

File tree

1 file changed

+164
-0
lines changed

1 file changed

+164
-0
lines changed

DataStructures/Stack/StackUtils.cs

Lines changed: 164 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,164 @@
1+
using System;
2+
using System.Collections.Generic;
3+
4+
/// <summary>
5+
///This is a stack-based utility in C-Sharp that can be used by other developers in their solutions.
6+
///This utility provides commonly used operations related to stacks, which can be beneficial for solving various problems such as expression evaluations, balanced parentheses, or maintaining a history of operations.
7+
8+
///MinStack: This custom stack keeps track of the minimum element so that getMin() can return the minimum in O(1) time.
9+
///Next Greater Element: For each element in an array, the utility finds the next greater element on the right side using a stack.
10+
///Balanced Parentheses Checker: It checks if an expression has matching and balanced parentheses.
11+
///Reverse a Stack: This utility reverses the elements in a stack using recursion.
12+
13+
///@author Mohit Singh
14+
///@author <a href="https://github.com/mohit-gogitter">mohit-gogitter<a>
15+
/// </summary>
16+
public class StackUtils
17+
{
18+
// 1. MinStack - Stack supporting push, pop, and retrieving minimum in O(1) time
19+
public class MinStack
20+
{
21+
private Stack<int> mainStack;
22+
private Stack<int> minStack;
23+
24+
public MinStack()
25+
{
26+
mainStack = new Stack<int>();
27+
minStack = new Stack<int>();
28+
}
29+
/// <summary>
30+
/// Adds an item on top of the stack.
31+
/// </summary>
32+
/// <param name="value">Item to be added on top of stack.</param>
33+
public void Push(int value)
34+
{
35+
mainStack.Push(value);
36+
if (minStack.Count == 0 || value <= minStack.Peek())
37+
{
38+
minStack.Push(value);
39+
}
40+
}
41+
42+
/// <summary>
43+
/// Removes an item from top of the stack.
44+
/// </summary>
45+
public void Pop()
46+
{
47+
if (mainStack.Count > 0)
48+
{
49+
int poppedValue = mainStack.Pop();
50+
if (poppedValue == minStack.Peek())
51+
{
52+
minStack.Pop();
53+
}
54+
}
55+
}
56+
57+
/// <summary>
58+
/// Fetches the minimum item from the stack and returns it.
59+
/// </summary>
60+
/// <returns>minimum item from the stack</returns>
61+
public int GetMin()
62+
{
63+
return minStack.Count == 0 ? int.MaxValue : minStack.Peek();
64+
}
65+
/// <summary>
66+
/// Removes an item from top of the stack and returns it.
67+
/// </summary>
68+
/// <returns>item on top of stack.</returns>
69+
public int Top()
70+
{
71+
return mainStack.Count == 0 ? -1 : mainStack.Peek();
72+
}
73+
/// <summary>
74+
/// Checks whether the stack is empty. Returns True if found empty else False.
75+
/// </summary>
76+
/// <returns>True or False</returns>
77+
public bool IsEmpty()
78+
{
79+
return mainStack.Count == 0;
80+
}
81+
}
82+
83+
// 2. Next Greater Element for each element in an array
84+
/// <summary>
85+
/// For each element in an array, the utility finds the next greater element on the right side using a stack.
86+
/// </summary>
87+
/// <param name="nums">Integer Array for which NextGreaterElement needs to be computed</param>
88+
/// <returns>Interger Array</returns>
89+
public static int[] NextGreaterElement(int[] nums)
90+
{
91+
Stack<int> stack = new Stack<int>();
92+
int[] result = new int[nums.Length];
93+
94+
for (int i = nums.Length - 1; i >= 0; i--)
95+
{
96+
while (stack.Count > 0 && stack.Peek() <= nums[i])
97+
{
98+
stack.Pop();
99+
}
100+
result[i] = stack.Count == 0 ? -1 : stack.Peek();
101+
stack.Push(nums[i]);
102+
}
103+
return result;
104+
}
105+
106+
// 3. Balanced Parentheses Checker
107+
/// <summary>
108+
/// It checks if an expression has matching and balanced parentheses.
109+
/// </summary>
110+
/// <param name="expression">string containing parenthesis</param>
111+
/// <returns>True or False</returns>
112+
public static bool IsBalanced(string expression)
113+
{
114+
Stack<char> stack = new Stack<char>();
115+
foreach (char c in expression)
116+
{
117+
if (c == '(' || c == '{' || c == '[')
118+
{
119+
stack.Push(c);
120+
}
121+
else if (c == ')' || c == '}' || c == ']')
122+
{
123+
if (stack.Count == 0) return false;
124+
char open = stack.Pop();
125+
if (!IsMatchingPair(open, c)) return false;
126+
}
127+
}
128+
return stack.Count == 0;
129+
}
130+
131+
private static bool IsMatchingPair(char open, char close)
132+
{
133+
return (open == '(' && close == ')') ||
134+
(open == '{' && close == '}') ||
135+
(open == '[' && close == ']');
136+
}
137+
138+
// 4. Reverse a Stack
139+
/// <summary>
140+
/// This utility reverses the elements in a stack using recursion.
141+
/// </summary>
142+
/// <param name="stack">A Stack of Generic Type</param>
143+
public static void ReverseStack<T>(Stack<T> stack)
144+
{
145+
if (stack.Count == 0) return;
146+
T temp = stack.Pop();
147+
ReverseStack(stack);
148+
InsertAtBottom(stack, temp);
149+
}
150+
151+
private static void InsertAtBottom<T>(Stack<T> stack, T value)
152+
{
153+
if (stack.Count == 0)
154+
{
155+
stack.Push(value);
156+
}
157+
else
158+
{
159+
T temp = stack.Pop();
160+
InsertAtBottom(stack, value);
161+
stack.Push(temp);
162+
}
163+
}
164+
}

0 commit comments

Comments
 (0)