on 3338699 help sign in
64 lines 1.4 kB history raw
1namespace StackImplementation
2{
3 internal class Stack<T>
4 {
5 private int _top;
6 private const int Capacity = 4;
7 private readonly T[] _stack = new T[Capacity];
9 public Stack()
10 {
11 _top = -1;
12 }
14 private bool IsEmpty()
15 {
16 return _top < 0;
17 }
18 private bool IsFull()
19 {
20 return _top == Capacity - 1;
21 }
23 public void Peek()
24 {
25 System.Console.WriteLine(!IsEmpty() ? $"The topmost element is: {_stack[_top]}" : "The stack is empty.");
26 }
28 public T Pop()
29 {
30 return !IsEmpty() ? _stack[_top--] : default;
31 }
33 public void Push(T element)
34 {
35 if (!IsFull())
36 {
37 _stack[++_top] = element;
38 }
39 else
40 {
41 System.Console.WriteLine("Cannot push - the stack is full.");
42 }
43 }
45 public override string ToString()
46 {
47 if (IsEmpty())
48 {
49 return "The stack is empty.";
50 }
52 var depiction = "";
54 for (var index = 0; index < _top; index++)
55 {
56 depiction += _stack[index].ToString() + ' ';
57 }
59 depiction += _stack[_top].ToString();
61 return $"Stack: [{depiction}]";
62 }
63 }