MCPcopy Create free account
hub / github.com/ByteByteGoHq/coding-interview-patterns / Queue

Class Queue

csharp/Stacks/ImplementAQueueUsingAStack.cs:1–42  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1public class Queue
2{
3 private Stack<int> _enqueueStack;
4 private Stack<int> _dequeueStack;
5
6 public Queue()
7 {
8 _enqueueStack = new Stack<int>();
9 _dequeueStack = new Stack<int>();
10 }
11
12 public void Enqueue(int x)
13 {
14 _enqueueStack.Push(x);
15 }
16
17 private void TransferEnqueueToDequeue()
18 {
19 // If the dequeue stack is empty, push all elements from the enqueue stack
20 // onto the dequeue stack. This ensures the top of the dequeue stack
21 // contains the most recent value.
22 if (_dequeueStack.Count == 0)
23 {
24 while (_enqueueStack.Count > 0)
25 _dequeueStack.Push(_enqueueStack.Pop());
26 }
27 }
28
29 public int? Dequeue()
30 {
31 TransferEnqueueToDequeue();
32
33 // Pop and return the value at the top of the dequeue stack.
34 return _dequeueStack.Count > 0 ? _dequeueStack.Pop() : null;
35 }
36
37 public int? Peek()
38 {
39 TransferEnqueueToDequeue();
40 return _dequeueStack.Count > 0 ? _dequeueStack.Peek() : null;
41 }
42}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected