Repository navigation
Expand file tree
/
Copy pathStack.cs
More file actions
65 lines (58 loc) · 1.45 KB
/
Copy pathStack.cs
File metadata and controls
65 lines (58 loc) · 1.45 KB
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 Code.StackDS;
/// <summary>
/// Stack data structure.
/// </summary>
/// <typeparam name="T"></typeparam>
public class Stack<T>
{
private List<T> items;
/// <summary>
/// Constructor to initialize the stack.
/// </summary>
/// <param name="data"></param>
public Stack()
{
items = [];
}
/// <summary>
/// Add an element to the stack.
/// </summary>
/// <param name="data"></param>
public void Push(T data)
{
items.Add(data);
}
/// <summary>
/// Remove and return the top element from the stack.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public T Pop()
{
if (items.Count == 0)
{
throw new InvalidOperationException("Stack is empty.");
}
var item = items[^1];
items.RemoveAt(items.Count - 1);
return item;
}
/// <summary>
/// Return the top element from the stack without removing it.
/// </summary>
/// <returns></returns>
/// <exception cref="InvalidOperationException"></exception>
public T Peek()
{
if (items.Count == 0)
{
throw new InvalidOperationException("Stack is empty.");
}
return items[^1];
}
public bool IsEmpty => items.Count == 0;
public int Count => items.Count;
public List<T> Items => items;
}