-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path232-Implement-Queue-using-Stacks.cs
More file actions
51 lines (44 loc) · 1.09 KB
/
Copy path232-Implement-Queue-using-Stacks.cs
File metadata and controls
51 lines (44 loc) · 1.09 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
// Push: O(1)
// Pop: O(1) amortized -- generally will be O(1) unless qStack empty, then O(n)
// Peek: O(1) same as pop
// Empty: O(1)
public class MyQueue
{
// Push: we can always push to same stack
// Pop: we will rely on second stack to simulate a queue. if it's empty, pop all elems from push stack to queue stack. pop top of stack for first elem
// Peek: peek is same as push except we peek first elem
// Empty: true if both stack counts are 0
Stack<int> pushStack;
Stack<int> qStack;
public MyQueue()
{
pushStack = new();
qStack = new();
}
public void Push(int x)
{
pushStack.Push(x);
}
public int Pop()
{
PrepQueue();
return qStack.Pop();
}
public int Peek()
{
PrepQueue();
return qStack.Peek();
}
private void PrepQueue()
{
if (qStack.Count == 0)
{
while (pushStack.Count > 0)
qStack.Push(pushStack.Pop());
}
}
public bool Empty()
{
return qStack.Count == 0 && pushStack.Count == 0;
}
}