-
Notifications
You must be signed in to change notification settings - Fork 55
/
74.MaxStack.cs
80 lines (67 loc) · 1.59 KB
/
74.MaxStack.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
//Design a stack that supports push, pop, top, and retrieving the maximum 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 maximum 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 maximum element
using System;
using System.Collections.Generic;
using System.Collections;
namespace MaxStack
{
public class MaxStack
{
private Stack<int> GeneralStack;
private Stack<int> MaximumStack;
public MaxStack()
{
GeneralStack = new Stack<int> ();
MaximumStack = new Stack<int> ();
}
public void Push(int x)
{
GeneralStack.Push (x);
if (MaximumStack.Count == 0 || x >= MaximumStack.Peek ())
MaximumStack.Push (x);
}
public void Pop()
{
if (GeneralStack.Count == 0)
return;
int temp = GeneralStack.Pop();
if (temp == MaximumStack.Peek ())
MaximumStack.Pop ();
}
public int Top()
{
if (GeneralStack.Count == 0)
return 0;
return GeneralStack.Peek ();
}
public int GetMin()
{
if (MaximumStack.Count == 0)
return 0;
return MaximumStack.Peek ();
}
}
class MainClass
{
public static void Main (string[] args)
{
MaxStack tStack = new MaxStack ();
tStack.Push (512);
tStack.Push (1024);
tStack.Push (1024);
tStack.Push (512);
tStack.Pop ();
Console.WriteLine (tStack.GetMin ());
tStack.Pop ();
Console.WriteLine (tStack.GetMin ());
tStack.Pop ();
Console.WriteLine (tStack.GetMin ());
}
}
}