-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Expand file tree
/
Copy pathProblem1.cs
More file actions
73 lines (60 loc) · 1.63 KB
/
Problem1.cs
File metadata and controls
73 lines (60 loc) · 1.63 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
// Time Complexity : O(n) ammortized time complexity
// Space Complexity : O(n)
// Did this code successfully run on Leetcode : Yes
// Any problem you faced while coding this : No
// Your code here along with comments explaining your approach
/*
I maintian two stacks - an in-stack which is solely used for pushing elements into the queue and an out-stack which is solely used for
removing elements from the queue. Every insert operation into the queue is performed by pushing the element to the in-stack.
Before performing any pop/peek operation, we check if out-stack is empty, if so then we transfer all the elements from in stack to out stack.
Every peek and pop operation is performed on the out stack.
*/
public class MyQueue
{
Stack<int> inStack;
Stack<int> outStack;
public MyQueue()
{
inStack = new();
outStack = new();
}
public void Push(int x)
{
inStack.Push(x);
}
public int Pop()
{
if (outStack.Count == 0)
{
Transfer();
}
return outStack.Pop();
}
public int Peek()
{
if (outStack.Count == 0)
{
Transfer();
}
return outStack.Peek();
}
public bool Empty()
{
return inStack.Count == 0 && outStack.Count == 0;
}
private void Transfer()
{
while (inStack.Count != 0)
{
outStack.Push(inStack.Pop());
}
}
}
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = new MyQueue();
* obj.Push(x);
* int param_2 = obj.Pop();
* int param_3 = obj.Peek();
* bool param_4 = obj.Empty();
*/