forked from TheAlgorithms/C-Sharp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ReverseStack.cs
44 lines (41 loc) · 1.28 KB
/
ReverseStack.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
using System;
using System.Collections.Generic;
namespace Algorithms.Stack
{
/// <summary>
/// Reverses the elements in a stack using recursion.
/// @author Mohit Singh. <a href="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/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);
}
}
}
}