-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0225-Implement-stack-using-queues.cs
More file actions
74 lines (60 loc) · 1.79 KB
/
0225-Implement-stack-using-queues.cs
File metadata and controls
74 lines (60 loc) · 1.79 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
using System;
using System.Collections.Generic;
using System.Text;
namespace Solution._0225.Implement_stack_using_queues
{
public class _0225_Implement_stack_using_queues
{
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.Push(x);
* int param_2 = obj.Pop();
* int param_3 = obj.Top();
* bool param_4 = obj.Empty();
*/
public class MyStack
{
/** Initialize your data structure here. */
Queue<int> queue;
Queue<int> temp;
public MyStack()
{
queue = new Queue<int>();
}
/** Push element x onto stack. */
public void Push(int x)
{
queue.Enqueue(x);
}
/** Removes the element on top of the stack and returns that element. */
public int Pop()
{
if (Empty()) return -1;
temp = new Queue<int>();
while (queue.Count > 1)
temp.Enqueue(queue.Dequeue());
int pop = queue.Dequeue();
queue = temp;
return pop;
}
/** Get the top element. */
public int Top()
{
if (Empty()) return -1;
temp = new Queue<int>();
while (queue.Count > 1)
temp.Enqueue(queue.Dequeue());
int top = queue.Dequeue();
temp.Enqueue(top);
queue = temp;
return top;
}
/** Returns whether the stack is empty. */
public bool Empty()
{
return queue.Count == 0;
}
}
}
}