forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QueueBasedStack.cs
75 lines (62 loc) · 1.95 KB
/
QueueBasedStack.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DataStructures.Stack;
public class QueueBasedStack<T>
{
private readonly Queue<T> queue;
public QueueBasedStack() => queue = new Queue<T>();
/// <summary>
/// Clears the stack.
/// </summary>
public void Clear() => queue.Clear();
public bool IsEmpty() => queue.Count == 0;
/// <summary>
/// Adds an item on top of the stack.
/// </summary>
/// <param name="item">Item to be added on top of stack.</param>
public void Push(T item) => queue.Enqueue(item);
/// <summary>
/// Removes an item from top of the stack and returns it.
/// </summary>
/// <returns>item on top of stack.</returns>
/// <exception cref="InvalidOperationException">Throw if stack is empty.</exception>
public T Pop()
{
if (IsEmpty())
{
throw new InvalidOperationException("The stack contains no items.");
}
for (int i = 0; i < queue.Count - 1; i++)
{
queue.Enqueue(queue.Dequeue());
}
return queue.Dequeue();
}
/// <summary>
/// return an item from the top of the stack without removing it.
/// </summary>
/// <returns>item on top of the stack.</returns>
/// <exception cref="InvalidOperationException">Throw if stack is empty.</exception>
public T Peek()
{
if (IsEmpty())
{
throw new InvalidOperationException("The stack contains no items.");
}
for (int i = 0; i < queue.Count - 1; i++)
{
queue.Enqueue(queue.Dequeue());
}
var item = queue.Peek();
queue.Enqueue(queue.Dequeue());
return item;
}
/// <summary>
/// returns the count of items on the stack.
/// </summary>
/// <returns>number of items on the stack.</returns>
public int Length() => queue.Count;
}