58 lines
1.6 KiB
C#
58 lines
1.6 KiB
C#
using System.Collections.Generic;
|
|
|
|
namespace Sarand.Net.Standard.Base.Core
|
|
{
|
|
//=======================================================================
|
|
/// <summary>
|
|
/// Stack (LIFO) with limit on length.
|
|
/// </summary>
|
|
/// <typeparam name="ITEM"></typeparam>
|
|
public class StackLimited<ITEM>
|
|
{
|
|
//-------------------------------------------------------------------
|
|
// Data members.
|
|
private int limit = 0;
|
|
private readonly LinkedList<ITEM> items = new LinkedList<ITEM>();
|
|
//-------------------------------------------------------------------
|
|
// Construction.
|
|
public StackLimited (int limit = 0)
|
|
{
|
|
this.limit = limit;
|
|
}
|
|
//-------------------------------------------------------------------
|
|
// Utilities.
|
|
public int Count
|
|
{
|
|
get { return items.Count; }
|
|
}
|
|
public void Clear ()
|
|
{
|
|
items.Clear();
|
|
}
|
|
//-------------------------------------------------------------------
|
|
/// <summary>
|
|
/// Add item to the stack and ensure limit isn't exceeded.
|
|
/// </summary>
|
|
/// <param name="item"></param>
|
|
public void Push (ITEM item)
|
|
{
|
|
items.AddFirst(item);
|
|
while (limit > 0 && items.Count > limit)
|
|
items.RemoveLast();
|
|
}
|
|
//-------------------------------------------------------------------
|
|
/// <summary>
|
|
/// Retrieve and remove last item added to the stack.
|
|
/// </summary>
|
|
/// <returns></returns>
|
|
public ITEM Pop ()
|
|
{
|
|
ITEM item = items.First.Value;
|
|
items.RemoveFirst();
|
|
return item;
|
|
}
|
|
//-------------------------------------------------------------------
|
|
}
|
|
//=======================================================================
|
|
}
|