-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGenericQueueImplementationUsingTwoStacks.cs
71 lines (61 loc) · 2.08 KB
/
GenericQueueImplementationUsingTwoStacks.cs
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
using System;
namespace dojo
{
public class GenericQueueImplementationUsingTwoStacks<T>
{
private readonly GenericStackFromLinkedListImplementation<T> _originalStack;
private readonly GenericStackFromLinkedListImplementation<T> _stackAllowingModifications;
public GenericQueueImplementationUsingTwoStacks(Node<T> node = null)
{
_originalStack = new GenericStackFromLinkedListImplementation<T>(node);
_stackAllowingModifications = new GenericStackFromLinkedListImplementation<T>();
}
public void Enqueue(Node<T> node)
{
_originalStack.Push(node);
}
public void Enqueue(T value)
{
_originalStack.Push(value);
}
public int Count => _originalStack.Count;
public Node<T> Peek()
{
MoveFromOriginalStackToModification();
var nodeToReturn = _stackAllowingModifications.Peek;
MoveFromModificationToOriginal();
return nodeToReturn;
}
public Node<T> Dequeue()
{
MoveFromOriginalStackToModification();
var nodeToReturn = _stackAllowingModifications.Pop;
MoveFromModificationToOriginal();
return nodeToReturn;
}
public void ShowMembers()
{
MoveFromOriginalStackToModification();
_stackAllowingModifications.ShowMembers();
MoveFromModificationToOriginal();
}
private void MoveFromOriginalStackToModification()
{
while (_originalStack.Peek != null)
{
var node = _originalStack.Pop;
node.NextNode = null;
_stackAllowingModifications.Push(node);
}
}
private void MoveFromModificationToOriginal()
{
while (_stackAllowingModifications.Peek != null)
{
var node = _stackAllowingModifications.Pop;
node.NextNode = null;
_originalStack.Push(node);
}
}
}
}