-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathStack.cs
61 lines (53 loc) · 1.45 KB
/
Stack.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
using System;
/*
We can implement our own (faster) count rather than LinkedList.Count()
because we don't allow access to the list directly.
*/
namespace PracticeQuestionsSharp.DataStructures
{
//Stack implementation using my linked list.
public class Stack<T>
{
public Stack()
{
list = new LinkedList<T>();
Count = 0;
}
public Stack<T> Push(T data)
{
list.Add(data);
Count++;
return this;
}
public T Pop()
{
if (IsEmpty) throw new InvalidOperationException("Stack empty.");
T result = list.Tail.Data;
list.RemoveNode(list.Tail);
Count--;
return result;
}
public T Peek()
{
return list.Tail.Data;
}
//Poor implementation of this since default(T) could be a useful value for some types (int, char).
// As long as you aren't using those default values however, it does the job.
public T TryPeek()
{
return IsEmpty ? default(T) : list.Tail.Data;
}
public void Clear()
{
list.Clear();
Count = 0;
}
public void Print(bool reverse = false)
{
list.Print(reverse);
}
public bool IsEmpty => Count == 0;
public int Count { get; private set; }
private readonly LinkedList<T> list;
}
}