-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.cs
More file actions
42 lines (36 loc) · 972 Bytes
/
ArrayStack.cs
File metadata and controls
42 lines (36 loc) · 972 Bytes
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
using System;
namespace DataStructures
{
/// <summary>Resizable array-based stack.</summary>
public class ArrayStack<T>
{
private T[] _a;
private int _top;
public ArrayStack(int capacity = 4)
{
if (capacity <= 0) throw new ArgumentOutOfRangeException(nameof(capacity));
_a = new T[capacity];
_top = 0;
}
public int Count => _top;
public bool IsEmpty => _top == 0;
public void Push(T item)
{
if (_top == _a.Length) Grow();
_a[_top++] = item;
}
public T Pop()
{
if (IsEmpty) throw new InvalidOperationException("Empty stack");
var val = _a[--_top];
_a[_top] = default!;
return val;
}
private void Grow()
{
var b = new T[_a.Length * 2];
Array.Copy(_a, b, _a.Length);
_a = b;
}
}
}