-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathReverseStack.cs
More file actions
40 lines (37 loc) · 1.09 KB
/
ReverseStack.cs
File metadata and controls
40 lines (37 loc) · 1.09 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
namespace Algorithms.Stack;
/// <summary>
/// Reverses the elements in a stack using recursion.
/// @author Mohit Singh. <a href="https://github.com/mohit-gogitter">mohit-gogitter</a>
/// </summary>
public class ReverseStack
{
/// <summary>
/// Recursively reverses the elements of the specified stack.
/// </summary>
/// <typeparam name="T">The type of elements in the stack.</typeparam>
/// <param name="stack">The stack to be reversed. This parameter cannot be null.</param>
/// <exception cref="ArgumentNullException">Thrown when the stack parameter is null.</exception>
public void Reverse<T>(Stack<T> stack)
{
if (stack.Count == 0)
{
return;
}
T temp = stack.Pop();
Reverse(stack);
InsertAtBottom(stack, temp);
}
private void InsertAtBottom<T>(Stack<T> stack, T value)
{
if (stack.Count == 0)
{
stack.Push(value);
}
else
{
T temp = stack.Pop();
InsertAtBottom(stack, value);
stack.Push(temp);
}
}
}