-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.cs
More file actions
108 lines (95 loc) · 1.92 KB
/
MinStack.cs
File metadata and controls
108 lines (95 loc) · 1.92 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
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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using System;
using System.Collections;
namespace ConsoleApp144
{
public class MyStack
{
private readonly Stack _stack;
private int _minElement;
public MyStack()
{
_stack = new Stack();
}
public void GetMin()
{
if (_stack.Count == 0)
{
Console.WriteLine("Stack is empty");
}
else
{
Console.WriteLine("Minimum element in stack is " + _minElement);
}
}
public void Peek()
{
if (_stack.Count == 0)
{
Console.WriteLine("Stack is empty");
return;
}
var t = (int) _stack.Peek();
Console.WriteLine("Top most element is : ");
if (t < _minElement)
Console.WriteLine(_minElement);
else
Console.WriteLine(t);
}
public void Pop()
{
if (_stack.Count == 0)
{
Console.WriteLine("Stack is empty");
return;
}
Console.Write("Top Most element removed : ");
var t = (int) _stack.Pop();
if (t < _minElement)
{
Console.WriteLine(_minElement);
_minElement = 2 * _minElement - t;
}
else
{
Console.WriteLine(t);
}
}
public void Push(int x)
{
if (_stack.Count == 0)
{
_minElement = x;
_stack.Push(x);
Console.WriteLine("Number inserted : " +x);
return;
}
if (x < _minElement)
{
_stack.Push(2 * x - _minElement);
_minElement = x;
}
else
{
_stack.Push(x);
}
Console.WriteLine("Number inserted is " +x);
}
}
static class Program
{
private static void Main()
{
var myStack = new MyStack();
myStack.Push(3);
myStack.Push(5);
myStack.Push(36);
myStack.Push(2);
myStack.Push(6);
myStack.Push(8);
myStack.Push(1);
myStack.GetMin();
myStack.Pop();
myStack.Peek();
}
}
}