-
Notifications
You must be signed in to change notification settings - Fork 0
/
dcp-053-queue-via-two-stacks.linq
62 lines (50 loc) · 1.18 KB
/
dcp-053-queue-via-two-stacks.linq
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
<Query Kind="Program" />
// This problem was asked by Apple.
//
// Implement a queue using two stacks. Recall that a queue
// is a FIFO (first-in, first-out) data structure with the
// following methods: enqueue, which inserts an element
// into the queue, and dequeue, which removes it.
void Main()
{
var queue = new MyQueue<int>();
queue.Enqueue(1);
queue.Enqueue(2);
queue.Enqueue(3);
queue.Enqueue(4);
queue.Dequeue().Dump("1");
queue.Dequeue().Dump("2");
queue.Dequeue().Dump("3");
queue.Enqueue(5);
queue.Enqueue(6);
queue.Dequeue().Dump("4");
queue.Dequeue().Dump("5");
queue.Dequeue().Dump("6");
}
public class MyQueue<T>
{
private Stack<T> _straight;
private Stack<T> _inverted;
public MyQueue()
{
_straight = new Stack<T>();
_inverted = new Stack<T>();
}
public void Enqueue(T element)
{
_straight.Push(element);
}
public T Dequeue()
{
// when inverted is empty move from another stack reversing the order
if (_inverted.Count == 0)
{
if (_straight.Count == 0)
throw new Exception("Queue is empty");
while (_straight.Count > 0)
_inverted.Push(_straight.Pop());
}
// return from inverted stack
return _inverted.Pop();
}
}