-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathArrayStack.cs
More file actions
45 lines (36 loc) · 950 Bytes
/
ArrayStack.cs
File metadata and controls
45 lines (36 loc) · 950 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
43
44
45
using System;
namespace AlgorithmsAndDataStructures.DataStructures.Stack;
public class ArrayStack<T>
{
private int pointer;
private T[] stack;
public ArrayStack(int initialCapacity = 8)
{
stack = new T[initialCapacity];
}
public bool IsEmpty => pointer == 0;
public void Push(T value)
{
if (pointer == stack.Length)
{
var newStack = new T[stack.Length * 2];
Array.Copy(stack, 0, newStack, 0, stack.Length);
stack = newStack;
}
stack[pointer] = value;
pointer++;
}
public T Pop()
{
if (IsEmpty) throw new ArgumentException("Stack is Empty");
var value = stack[pointer - 1];
stack[pointer - 1] = default;
pointer--;
return value;
}
public T Peak()
{
if (IsEmpty) throw new ArgumentException("Stack is Empty");
return stack[pointer - 1];
}
}