Skip to content

Instantly share code, notes, and snippets.

@D34NM
Created March 23, 2017 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save D34NM/f910700d72dff345aff4723bfc8abe9a to your computer and use it in GitHub Desktop.
Save D34NM/f910700d72dff345aff4723bfc8abe9a to your computer and use it in GitHub Desktop.
Basic implementation of Stack.
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