-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathStack with list.cs
84 lines (66 loc) · 1.77 KB
/
Stack with list.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
Stack myStack = new Stack();
Console.WriteLine("Is Empty: " + myStack.IsEmpty());
Console.WriteLine("Item Added: " + myStack.Push(10));
Console.WriteLine("Item Added: " + myStack.Push(20));
Console.WriteLine("Item Added: " + myStack.Push(30));
Console.WriteLine("Item Added: " + myStack.Push(40));
Console.WriteLine("Is Empty: " + myStack.IsEmpty());
Console.Write("Printing stack: "); myStack.PrintStack();
Console.WriteLine("Peek: " + myStack.Peek());
Console.WriteLine("Pop: " + myStack.Pop());
Console.WriteLine("Pop: " + myStack.Pop());
Console.WriteLine("Pop: " + myStack.Pop());
Console.Write("Printing stack: "); myStack.PrintStack();
Console.WriteLine("Pop: " + myStack.Pop());
Console.WriteLine("Is Empty: " + myStack.IsEmpty());
/*Exception validations
Console.WriteLine("Peek: " + myStack.Peek());
Console.WriteLine("Pop: " + myStack.Pop());
myStack.PrintStack();
*/
public class Stack
{
List<int> Elements = new();
int Top = -1;
//O(1)
public bool IsEmpty()
{
return Elements.Count == 0;
}
//O(1)
public int Push(int data)
{
Elements.Add(data);
Top++;
return data;
}
//O(1)
public int Pop()
{
ValidateStack();
int itemToBeRemoved = Elements[Top];
Elements.RemoveAt(Top);
Top--;
return itemToBeRemoved;
}
//O(1)
public int Peek()
{
ValidateStack();
return Elements[Top];
}
//O(n)
public void PrintStack()
{
ValidateStack();
for (int i = Elements.Count-1; i >=0 ; i--)
{
Console.Write(Elements[i] + " ");
}
Console.WriteLine();
}
private void ValidateStack()
{
if (Top < 0) throw new InvalidOperationException("Stack is Empty!");
}
}