-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
57 lines (42 loc) · 1005 Bytes
/
Program.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
var stack = new Stack();
for (var i = 1; i <= 17; i++)
{
stack.Push(i * 100);
}
while (!stack.IsEmpty())
{
Console.WriteLine($"Peek: {stack.Peek()}");
Console.WriteLine($"Pop: {stack.Pop()}");
}
class Stack
{
private int[] _items;
private int _pivot;
public Stack()
{
_pivot = -1;
_items = new int[4];
}
public void Push(int item)
{
_resize();
_items[++_pivot] = item;
}
public int Pop()
{
if(IsEmpty()) throw new InvalidOperationException("Stack is empty");
return _items[_pivot--];
}
public int Peek()
=> _items[_pivot];
public bool IsEmpty()
=> _pivot == -1;
private void _resize()
{
if(_pivot < _items.Length - 1) return;
Console.WriteLine($"Resizing stack from {_items.Length} to {_items.Length * 2}");
var copy = new int[_items.Length * 2];
Array.Copy(_items, copy, _items.Length);
_items = copy;
}
}