Repository navigation
Expand file tree
/
Copy pathStackLinkedListBase.cs
More file actions
91 lines (80 loc) · 2.55 KB
/
Copy pathStackLinkedListBase.cs
File metadata and controls
91 lines (80 loc) · 2.55 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
80
81
82
83
84
85
86
87
88
89
90
91
using System;
namespace Stack
{
/// <summary>
/// A generic linked list-based stack implementation.
/// </summary>
internal class StackLinkedListBase<T>
{
private Node<T>? head; // The head node of the linked list
/// <summary>
/// Initializes an empty stack.
/// </summary>
public StackLinkedListBase()
{
head = null;
}
/// <summary>
/// Removes and returns the top element of the stack.
/// </summary>
/// <returns>The top element of the stack.</returns>
/// <exception cref="InvalidOperationException">Thrown if the stack is empty.</exception>
public T Pop()
{
if (head == null)
{
throw new InvalidOperationException("Stack underflow: no elements to pop.");
}
T temp = head.Data; // Retrieve the data from the head node
head = head.Next; // Move the head pointer to the next node
return temp;
}
/// <summary>
/// Adds a new element to the top of the stack.
/// </summary>
public void Push(T data)
{
// Create a new node and make it the new head
head = new Node<T>(data, head);
}
/// <summary>
/// Prints all the elements in the stack from top to bottom.
/// </summary>
public void Print()
{
if (head == null)
{
Console.WriteLine("Empty stack");
return;
}
Node<T>? current = head;
while (current != null)
{
Console.WriteLine(current.Data);
current = current.Next;
}
}
}
/// <summary>
/// A generic node class used for the linked list implementation.
/// </summary>
public class Node<T>
{
public T Data { get; set; } // The data stored in the node
public Node<T>? Next { get; set; } // Reference to the next node
/// <summary>
/// Default constructor for an empty node.
/// </summary>
public Node() { }
/// <summary>
/// Constructor to initialize a node with data and a reference to the next node.
/// </summary>
/// <param name="data">The data to store in the node.</param>
/// <param name="next">The reference to the next node.</param>
public Node(T data, Node<T>? next)
{
Data = data;
Next = next;
}
}
}