-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathQueueStack.cs
More file actions
61 lines (47 loc) · 1.34 KB
/
QueueStack.cs
File metadata and controls
61 lines (47 loc) · 1.34 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
using System;
using System.Collections.Generic;
namespace AlgorithmsAndDataStructures.DataStructures.Stack;
public class QueueStack<T>
{
private readonly Queue<T> leftQueue;
private readonly Queue<T> rightQueue;
public QueueStack()
{
leftQueue = new Queue<T>();
rightQueue = new Queue<T>();
}
public bool IsEmpty => rightQueue.Count == 0 && leftQueue.Count == 0;
public void Push(T value)
{
if (leftQueue.Count > 0)
leftQueue.Enqueue(value);
else if (rightQueue.Count > 0)
rightQueue.Enqueue(value);
else
leftQueue.Enqueue(value);
}
public T Pop()
{
if (IsEmpty) throw new ArgumentException("Stack is Empty");
return GetPopQueue().Dequeue();
}
public T Peak()
{
if (IsEmpty) throw new ArgumentException("Stack is Empty");
return GetPopQueue().Peek();
}
private Queue<T> GetPopQueue()
{
if (leftQueue.Count > 0)
{
while (leftQueue.Count > 1) rightQueue.Enqueue(leftQueue.Dequeue());
return leftQueue;
}
if (rightQueue.Count > 0)
{
while (rightQueue.Count > 1) leftQueue.Enqueue(rightQueue.Dequeue());
return rightQueue;
}
throw new ArgumentException("Stack is Empty");
}
}