Created
March 23, 2017 19:03
-
-
Save D34NM/f910700d72dff345aff4723bfc8abe9a to your computer and use it in GitHub Desktop.
Basic implementation of Stack.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace DataStructures | |
{ | |
public class Stack<T> | |
{ | |
#region Fields | |
private int _count; | |
private T[] _values; | |
#endregion | |
public Stack() | |
{ | |
_values = new T[4]; | |
} | |
public Stack(int capacity) | |
{ | |
if (capacity < 0) | |
throw new ArgumentOutOfRangeException(nameof(capacity)); | |
_values = new T[capacity]; | |
} | |
#region Properties | |
public int Count { get { return _count; } } | |
#endregion | |
public void Push(T data) | |
{ | |
if (_values.Length <= _count) | |
Grow(); | |
_values[_count] = data; | |
_count++; | |
} | |
public T Pop() | |
{ | |
if (_count <= 0) | |
throw new ArgumentOutOfRangeException(); | |
--_count; | |
if ((_count * 4) <= _values.Length) | |
Shrink(); | |
T retValue = _values[_count]; | |
_values[_count] = default(T); | |
return retValue; | |
} | |
private void Grow() | |
{ | |
T[] temp = new T[_values.Length * 2]; | |
for (int i = 0; i < _values.Length; i++) | |
{ | |
temp[i] = _values[i]; | |
} | |
_values = temp; | |
} | |
private void Shrink() | |
{ | |
T[] temp = new T[_values.Length / 4]; | |
for (int i = 0; i < temp.Length; i++) | |
{ | |
temp[i] = _values[i]; | |
} | |
_values = temp; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment