-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLimitedStack.cs
More file actions
44 lines (36 loc) · 1.03 KB
/
LimitedStack.cs
File metadata and controls
44 lines (36 loc) · 1.03 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
namespace NoteWorthy;
/// <summary>
/// A stack that has a maximum size. If the stack is full and a new item is added, the oldest item is removed.
/// </summary>
/// <typeparam name="T"></typeparam>
class LimitedStack<T>
{
private readonly int maxSize;
private readonly LinkedList<T> stack;
public LimitedStack(int maxSize)
{
this.maxSize = maxSize;
stack = new LinkedList<T>();
}
public void Push(T item)
{
// If the stack is full, remove the oldest item (first in the LinkedList)
if (stack.Count >= maxSize)
{
stack.RemoveFirst();
}
stack.AddLast(item); // Add new item to the end (top of the stack)
}
public T Pop()
{
if (stack.Count == 0)
{
throw new InvalidOperationException("The stack is empty.");
}
T item = stack.Last.Value;
stack.RemoveLast(); // Remove the top item
return item;
}
public int Count => stack.Count;
public bool IsEmpty => stack.Count == 0;
}