-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLimitedSizeStack.cs
49 lines (42 loc) · 1.2 KB
/
LimitedSizeStack.cs
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
using System;
using System.Collections.Generic;
namespace TodoApplication
{
public class LimitedSizeStack<T>
{
private int _limit;
private readonly LinkedList<T> _linkedListStack = new LinkedList<T>();
public int Limit
{
set
{
if (value < 0)
throw new ArgumentOutOfRangeException("History length must be non negative");
_limit = value;
}
get => _limit;
}
public LimitedSizeStack(int limit) => _limit = limit;
public void Push(T item)
{
if (_limit == 0)
return;
if (_linkedListStack.Count < _limit)
_linkedListStack.AddLast(item);
else
{
_linkedListStack.RemoveFirst();
_linkedListStack.AddLast(item);
}
}
public T Pop()
{
if (_linkedListStack.Count == 0)
return (T) new object();
var last = _linkedListStack.Last;
_linkedListStack.RemoveLast();
return last.Value;
}
public int Count => _linkedListStack.Count;
}
}