LinkedList and a Limited Undo Stack

07
Jun
2008

LinkedList and a Limited Undo Stack

I needed an undo stack today - but wanted it to behave like a queue when it was full, dropping the oldest items in the collection to make room for new ones. Found two posts - Undo Functionality with a Limited Stack, and also a reference to an identically named collection called LimitedStack here. 

Was initially thinking of simply writing a wrapper over an array of objects, shifting items along as new ones were added, but using a linked list is a clever solution, as it provides the queue like behavior needed without out any extra code via RemoveFirst() and RemoveLast().

using System;
using System.Collections.Generic;

namespace DotBits.Gallery.Builder.Objects
{
    [Serializable()]
    public class UndoStack<T> : LinkedList<T>
    {
        private int _maxItems;

        public int MaxItems
        {
            get 
            {
               return _maxItems; 
            }
            set
            {
                while (this.Count > value)
                {
                    this.RemoveFirst();
                }
                
                _maxItems = value;
            }
        }

        public UndoStack(int max)
        {
            _maxItems = max;
        }

        public T Peek()
        {
            return this.Last.Value;
        }

        public T Pop()
        {
            LinkedListNode<T> node = this.Last;
            this.RemoveLast();
            return node.Value;
        }

        public void Push(T value)
        {
            LinkedListNode<T> node = new LinkedListNode<T>(value);
            this.AddLast(node);

            if (this.Count > _maxItems)
            {
                this.RemoveFirst();
            }
        }
    }
}
Category: