forked from iiitv/algos
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStack.cs
More file actions
149 lines (112 loc) · 2.71 KB
/
Stack.cs
File metadata and controls
149 lines (112 loc) · 2.71 KB
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
class MainClass
{
public static void Main()
{
Stack<string> test = new Stack<string>();
test.Push("123");
test.Push("test");
test.Push("rawr");
test.Push("Pancake");
test.Push("Yummy");
test.Push("321");
test.Push(":thinking:");
Console.WriteLine(test.ToString());
test.Rotate(4, true);
Console.WriteLine(test.ToString());
test.Rotate(5, false);
Console.WriteLine(test.ToString());
Console.WriteLine(test.Peek() + "\n");
while (!(test.IsEmpty()))
{
test.Pop();
Console.WriteLine(test.ToString());
}
}
}
class Stack<T>
{
private LinkedList<T> stack;
// Constructs an empty stack
public Stack()
{
stack = new LinkedList<T>();
}
// Adds element at the top of the stack
public void Push(T data)
{
stack.AddLast(data);
}
// Removes the element at the top of the stack
public T Pop()
{
if (IsEmpty())
return default(T);
T element = stack.Last();
stack.RemoveLast();
return element;
}
// Returns true if the stack is empty
public bool IsEmpty()
{
return (!stack.Any());
}
// Returns the last element of the stack
public T Peek()
{
if (IsEmpty())
return default(T);
return stack.Last();
}
/**
* gets the n top elements and rotates them
*
* if left == false then it will move the last element to behind the nth element(from the top)
*
* if left == true it will move the nth element(from the top) to the top
*/
public void Rotate(int n, bool left)
{
if (n <= 1)
return;
if (stack.Count < 2)
return;
n -= 1;
if (left)
{
LinkedListNode<T> node = stack.Last;
for (int i = 1; i <= n; ++i)
{
node = node.Previous;
}
T value = node.Value;
stack.Remove(value);
Push(value);
}
else
{
T last = stack.Last();
Pop();
LinkedListNode<T> node = stack.Last;
for (int i = 0; i < n; i++)
{
node = node.Previous;
}
stack.AddBefore(node.Next, last);
}
}
public override string ToString()
{
string s = "Stack: ";
foreach(T t in stack)
{
s += t.ToString() + " | ";
}
s += "\n";
return s;
}
}