-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackMin.cs
More file actions
46 lines (43 loc) · 1.16 KB
/
StackMin.cs
File metadata and controls
46 lines (43 loc) · 1.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
//Author: Maple0
//Github:https://github.com/Maple0
//13th Oct 2016
//Stack with Min method
public class StackMin
{
struct MinStackElement
{
public int data;
public int min;
}
int top = 0;
List<MinStackElement> _stackMin = new List<MinStackElement>();
public void Push(int data)
{
if (top == 0)
{
_stackMin.Add(new MinStackElement() { data = data, min = data });
}
else
{
var stackElement = new MinStackElement() { data = data, min = _stackMin[top-1].min };
if (stackElement.min > data)
stackElement.min = data;
_stackMin.Add(stackElement);
}
top++;
}
public int Pop()
{
int data= _stackMin[top-1].data;
_stackMin.RemoveAt(top-1);
top--;
return data;
}
public int GetMin()
{
if (top == 0)
throw new Exception("Stack is empty.");
var min = _stackMin[top-1].min;
return min;
}
}