-
Notifications
You must be signed in to change notification settings - Fork 56
/
73.MinStack.cs
82 lines (70 loc) · 1.68 KB
/
73.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
//push(x) -- Push element x onto stack.
//pop() -- Removes the element on top of the stack.
//top() -- Get the top element.
//getMin() -- Retrieve the minimum element in the stack.
//use two stacks:
//use the first stack to store all the elements
//use the second stack to keep track of the minmum element
using System;
using System.Collections.Generic;
using System.Collections;
namespace MinStack
{
public class MinStack
{
private Stack<int> GeneralStack;
private Stack<int> MinimumStack;
public MinStack()
{
GeneralStack = new Stack<int> ();
MinimumStack = new Stack<int> ();
}
public void Push(int x)
{
GeneralStack.Push (x);
if (MinimumStack.Count == 0 || x <= MinimumStack.Peek ()) //consider duplicate element!!
MinimumStack.Push (x);
}
public void Pop()
{
if (GeneralStack.Count == 0)
return;
int temp = GeneralStack.Pop ();
if (temp == MinimumStack.Peek ())
MinimumStack.Pop ();
}
public int Top()
{
if (GeneralStack.Count == 0)
return 0;
return GeneralStack.Peek ();
}
public int GetMin()
{
if (MinimumStack.Count == 0)
return 0;
return MinimumStack.Peek ();
}
}
class MainClass
{
public static void Main (string[] args)
{
MinStack tStack = new MinStack ();
tStack.Push (3);
tStack.Push (7);
tStack.Push (2);
tStack.Push (6);
tStack.Push (19);
tStack.Push (1);
tStack.Push (13);
Console.WriteLine (tStack.Top ());
Console.WriteLine (tStack.GetMin ());
tStack.Pop ();
tStack.Pop ();
Console.WriteLine (tStack.Top ());
Console.WriteLine (tStack.GetMin ());
}
}
}