-
Notifications
You must be signed in to change notification settings - Fork 2
/
Stack.cs
65 lines (57 loc) · 1.67 KB
/
Stack.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
using System;
using System.Collections.Generic;
namespace Task_6_1
{
public class Stack<T> where T : IComparable<T>
{
private const int MAX_STACK_SIZE = 100;
private T[] _stack;
private int _count;
private T[] _min;
private int _minCount;
public Stack()
{
_stack = new T[MAX_STACK_SIZE];
_count = 0;
_min = new T[MAX_STACK_SIZE];
_minCount = 0;
}
public Stack(int size)
{
if (size < 0) throw new ArgumentOutOfRangeException();
_stack = new T[size];
_count = 0;
_min = new T[size];
_minCount = 0;
}
private bool IsEmpty() => _count is 0 ? true : false;
private bool isFull() => _count >= _stack.Length - 1 ? true : false;
public T Pop()
{
if (IsEmpty()) throw new InvalidOperationException();
T value = _stack[_count];
_count--;
if (_min[_minCount - 1].Equals(value))
{
_min[_minCount - 1] = default(T);
_minCount--;
}
return value;
}
public void Push(T value)
{
if (isFull()) throw new StackOverflowException();
if (IsEmpty()) _min[_minCount++] = value;
if (value.CompareTo(_min[_minCount - 1]) < 0)
{
_min[_minCount++] = value;
}
_stack[++_count] = value;
}
public T Min()
{
if (IsEmpty()) throw new InvalidOperationException();
return _min[_minCount - 1];
}
}
}