Skip to content

Instantly share code, notes, and snippets.

@sapher
Created June 10, 2013 10:51
Show Gist options
  • Save sapher/5747929 to your computer and use it in GitHub Desktop.
Save sapher/5747929 to your computer and use it in GitHub Desktop.
Stack with a limited amount of element . When an element is added, the last element is removed. This class implements IEnumerable so it's possible to use it in a foreach for exemple.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Stack
{
[Serializable]
public class LimitedStack<T> : IEnumerable
{
#region Fields
private readonly int _limit;
private readonly LinkedList<T> _list;
#endregion
#region Constructors
public LimitedStack(int maxSize)
{
_limit = maxSize;
_list = new LinkedList<T>();
}
#endregion
#region Public Stack Implementation
public void Push(T value)
{
if (_list.Count == _limit)
{
_list.RemoveFirst();
}
_list.AddLast(value);
}
public T Pop()
{
if (_list.Count > 0)
{
T value = _list.Last.Value;
_list.RemoveLast();
return value;
}
throw new InvalidOperationException("The Stack is empty");
}
public T Peek()
{
if (_list.Count > 0)
{
T value = _list.First.Value;
return value;
}
throw new InvalidOperationException("The Stack is empty");
}
public void Clear()
{
_list.Clear();
}
public int Count
{
get { return _list.Count; }
}
/// <summary>
/// Checks if the top object on the stack matches the value passed in
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public bool IsTop(T value)
{
var result = false;
if (Count > 0)
{
result = Peek().Equals(value);
}
return result;
}
public bool Contains(T value)
{
var result = false;
if (Count > 0)
{
result = _list.Contains(value);
}
return result;
}
#endregion
public IEnumerator GetEnumerator()
{
return _list.GetEnumerator();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment