-
Notifications
You must be signed in to change notification settings - Fork 0
/
GenericStack.cs
71 lines (70 loc) · 1.41 KB
/
GenericStack.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
using System;
public class GenericStackItem<T>
{
private T value;
private GenericStackItem<T> next;
public GenericStackItem(T value)
{
this.value = value;
}
public void SetNext(GenericStackItem<T> nextItem)
{
next = nextItem;
}
public GenericStackItem<T> GetNext()
{
return next;
}
public T GetValue()
{
return value;
}
}
public class GenericStack<T>
{
private GenericStackItem<T> top;
public GenericStack()
{
top = null;
}
public bool IsEmpty()
{
return top == null;
}
public void Insert(T value)
{
var newItem = new GenericStackItem<T>(value);
if (top != null)
newItem.SetNext(top);
top = newItem;
}
public T Pop()
{
if (top == null)
return default(T);
var value = top.GetValue();
if (top.GetNext() != null)
top = top.GetNext();
else
top=null;
return value;
}
public GenericStackItem<T> Top()
{
return top;
}
public void Print()
{
Console.Write("STACK = {");
if (!IsEmpty())
{
var temp = top;
while (temp != null)
{
Console.Write(string.Format(" {0}", temp.GetValue()));
temp = temp.GetNext();
}
}
Console.WriteLine("}");
}
}