-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathMinStack.cs
49 lines (42 loc) · 1.19 KB
/
MinStack.cs
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
47
48
49
using PracticeQuestionsSharp.DataStructures;
using System;
namespace PracticeQuestionsSharp.Exercises.Stack
{
//Stack that can also return the minimum value in constant time.
public class MinStack<T> : Stack<T> where T : IComparable<T>
{
public new MinStack<T> Push(T data)
{
base.Push(data);
UpdateMin(data, true);
return this;
}
public new T Pop()
{
return UpdateMin(base.Pop(), false);
}
public new void Clear()
{
base.Clear();
minValues.Clear();
}
public T Min()
{
if (IsEmpty) throw new InvalidOperationException("Stack empty.");
return minValues.Peek();
}
private T UpdateMin(T data, bool push)
{
if (minValues.IsEmpty || data.CompareTo(minValues.Peek()) <= 0 && push)
{
minValues.Push(data);
}
else if (data.CompareTo(minValues.Peek()) == 0 && !push)
{
minValues.Pop();
}
return data;
}
private readonly Stack<T> minValues = new Stack<T>();
}
}