- Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathListBasedStack.cs
94 lines (81 loc) · 2.95 KB
/
ListBasedStack.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
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
92
93
94
usingSystem;
usingSystem.Collections.Generic;
namespaceDataStructures.Stack;
/// <summary>
/// Implementation of a list based stack. FILO style.
/// </summary>
/// <typeparam name="T">Generic Type.</typeparam>
publicclassListBasedStack<T>
{
/// <summary>
/// <see cref="List{T}" /> based stack.
/// </summary>
privatereadonlyLinkedList<T>stack;
/// <summary>
/// Initializes a new instance of the <see cref="ListBasedStack{T}" /> class.
/// </summary>
publicListBasedStack()=>stack=newLinkedList<T>();
/// <summary>
/// Initializes a new instance of the <see cref="ListBasedStack{T}" /> class.
/// </summary>
/// <param name="item">Item to push onto the <see cref="ListBasedStack{T}" />.</param>
publicListBasedStack(Titem)
:this()=>Push(item);
/// <summary>
/// Initializes a new instance of the <see cref="ListBasedStack{T}" /> class.
/// </summary>
/// <param name="items">Items to push onto the <see cref="ListBasedStack{T}" />.</param>
publicListBasedStack(IEnumerable<T>items)
:this()
{
foreach(variteminitems)
{
Push(item);
}
}
/// <summary>
/// Gets the number of elements on the <see cref="ListBasedStack{T}" />.
/// </summary>
publicintCount=>stack.Count;
/// <summary>
/// Removes all items from the <see cref="ListBasedStack{T}" />.
/// </summary>
publicvoidClear()=>stack.Clear();
/// <summary>
/// Determines whether an element is in the <see cref="ListBasedStack{T}" />.
/// </summary>
/// <param name="item">The item to locate in the <see cref="ListBasedStack{T}" />.</param>
/// <returns>True, if the item is in the stack.</returns>
publicboolContains(Titem)=>stack.Contains(item);
/// <summary>
/// Returns the item at the top of the <see cref="ListBasedStack{T}" /> without removing it.
/// </summary>
/// <returns>The item at the top of the <see cref="ListBasedStack{T}" />.</returns>
publicTPeek()
{
if(stack.Firstisnull)
{
thrownewInvalidOperationException("Stack is empty");
}
returnstack.First.Value;
}
/// <summary>
/// Removes and returns the item at the top of the <see cref="ListBasedStack{T}" />.
/// </summary>
/// <returns>The item removed from the top of the <see cref="ListBasedStack{T}" />.</returns>
publicTPop()
{
if(stack.Firstisnull)
{
thrownewInvalidOperationException("Stack is empty");
}
varitem=stack.First.Value;
stack.RemoveFirst();
returnitem;
}
/// <summary>
/// Inserts an item at the top of the <see cref="ListBasedStack{T}" />.
/// </summary>
/// <param name="item">The item to push onto the <see cref="ListBasedStack{T}" />.</param>
publicvoidPush(Titem)=>stack.AddFirst(item);
}