-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution3.cs
More file actions
80 lines (64 loc) · 2.04 KB
/
Solution3.cs
File metadata and controls
80 lines (64 loc) · 2.04 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace cSharpSolutions
{
internal class Solution3
{
private class Stack<T>
{
private T[] _items;
private int _count;
private int _capacity;
public Stack(int initialCapacity = 4)
{
_capacity = initialCapacity;
_items = new T[_capacity];
_count = 0;
}
public void Push(T item)
{
if (_count == _capacity)
{
_capacity *= 2;
Array.Resize(ref _items, _capacity);
}
_items[_count++] = item;
}
public T Pop()
{
if (IsEmpty())
throw new InvalidOperationException("Stack is empty.");
_count--;
T item = _items[_count];
_items[_count] = default!; // clear slot for GC
return item;
}
public T Peek()
{
if (IsEmpty())
throw new InvalidOperationException("Stack is empty.");
return _items[_count - 1];
}
public bool IsEmpty() => _count == 0;
public int Count() => _count;
}
public static void Run()
{
Console.WriteLine("=== Solution 3: Stack Implementation ===");
var stack = new Stack<int>();
stack.Push(1);
stack.Push(2);
stack.Push(3);
Console.WriteLine($"Stack count: {stack.Count()}");
Console.WriteLine($"Top element (peek): {stack.Peek()}");
Console.WriteLine("Popping elements:");
while (!stack.IsEmpty())
Console.WriteLine(stack.Pop());
Console.WriteLine($"Stack empty? {stack.IsEmpty()}");
Console.WriteLine("\nSolution 3 complete");
}
}
}