Friday, April 29, 2016

Stack Class in C#

So this week there is no more homework for my C# class since the semester is coming to an end and we have a final exam next week.

Since I was bored at work, I started thinking that we never created a stack for one of the class assignments. So I decided to create my own, which wasn't that hard since its essentially just a wrapper around an array.

I started to work on it yesterday for a couple hours and finished it this morning.

Here is my code:

using System;
using System.Collections;
using System.Collections.Generic;
class myStack<T> : IEnumerable<T>, ICollection, IEnumerable where T : IComparable<T>
{
private int ElementCount = 0;
private T[] UnderlyingArray;
public myStack(int starting_size)
{
if (starting_size > 5)
UnderlyingArray = new T[starting_size];
else
UnderlyingArray = new T[5];
}
public myStack()
{
UnderlyingArray = new T[5];
}
public myStack(ICollection<T> colletion)
{
UnderlyingArray = new T[colletion.Count];
foreach (T item in colletion)
Push(item);
}
public int Count
{
get
{
return ElementCount;
}
}
public void Push(T item)
{
if (ElementCount == UnderlyingArray.Length)
SizeUp();
UnderlyingArray[ElementCount] = item;
ElementCount++;
}
public T Peek()
{
return UnderlyingArray[ElementCount - 1];
}
public T Pop()
{
ElementCount--;
T last_item = UnderlyingArray[ElementCount];
UnderlyingArray[ElementCount] = default(T);
return last_item;
}
public void Clear()
{
UnderlyingArray = new T[UnderlyingArray.Length];
}
public void TrimExcess()
{
if (GetRatio() < .9)
SizeDown();
}
public bool Contains(T item)
{
foreach (T existing_item in UnderlyingArray)
if (item.CompareTo(existing_item) == 0)
return true;
return false;
}
public bool IsSynchronized
{
get
{
return false;
}
}
public object SyncRoot
{
get
{
return this;
}
}
public void CopyTo(Array array, int index)
{
int start = index;
for (int i = 0; i < ElementCount; i++)
{
array.SetValue(UnderlyingArray[i], start);
start++;
}
}
public T[] ToArray()
{
int count = ElementCount;
T[] output = new T[count];
for (int index = 0; index < count; index++)
output[index] = Pop();
return output;
}
public IEnumerator<T> GetEnumerator()
{
for (int index = ElementCount - 1; index >= 0; index--)
yield return UnderlyingArray[index];
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
private void SizeUp()
{
T[] new_array = new T[UnderlyingArray.Length * 2];
for (int index = 0; index < ElementCount; index++)
new_array[index] = UnderlyingArray[index];
UnderlyingArray = new_array;
}
private void SizeDown()
{
T[] new_array = new T[ElementCount];
for (int index = 0; index < ElementCount; index++)
new_array[index] = UnderlyingArray[index];
UnderlyingArray = new_array;
}
private double GetRatio()
{
return ElementCount / UnderlyingArray.Length;
}
}
view raw myStack.cs hosted with ❤ by GitHub

Thanks for reading!

No comments:

Post a Comment