/
022_StackWithTwoQueues.cs
92 lines (75 loc) · 2.17 KB
/
022_StackWithTwoQueues.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// Coding Interviews: Questions, Analysis & Solutions
// Harry He
using System;
using System.Collections.Generic;
namespace StackWithQueues
{
public class StackWithTwoQueues<T>
{
public void Push(T item)
{
if (queue2.Count != 0)
queue2.Enqueue(item);
else
queue1.Enqueue(item);
}
public T Pop()
{
if (queue1.Count == 0 && queue2.Count == 0)
throw new InvalidOperationException("Stack is Empty");
Queue<T> emptyQueue = queue1;
Queue<T> nonemptyQueue = queue2;
if (queue1.Count > 0)
{
emptyQueue = queue2;
nonemptyQueue = queue1;
}
while (nonemptyQueue.Count > 1)
emptyQueue.Enqueue(nonemptyQueue.Dequeue());
return nonemptyQueue.Dequeue();
}
private Queue<T> queue1 = new Queue<T>();
private Queue<T> queue2 = new Queue<T>();
}
class Program
{
static void Test(char actual, char expected)
{
if (actual == expected)
Console.WriteLine("Test passed.");
else
Console.WriteLine("Test failed.");
}
static void Main(string[] args)
{
StackWithTwoQueues<char> stack = new StackWithTwoQueues<char>();
stack.Push('a');
stack.Push('b');
stack.Push('c');
char top = stack.Pop();
Test(top, 'c');
top = stack.Pop();
Test(top, 'b');
stack.Push('d');
top = stack.Pop();
Test(top, 'd');
top = stack.Pop();
Test(top, 'a');
try
{
top = stack.Pop();
Console.WriteLine("Test failed.");
}
catch (InvalidOperationException)
{
Console.WriteLine("Test passed.");
}
stack.Push('e');
stack.Push('f');
top = stack.Pop();
Test(top, 'f');
top = stack.Pop();
Test(top, 'e');
}
}
}