Sunday, June 08, 2008
Sunday, June 08, 2008 12:35:26 AM (SE Asia Standard Time, UTC+07:00) (C#)

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();
            }
        }
    }
}

OpenID
Please login with either your OpenID above, or your details below.
Name
E-mail
(will show your gravatar icon)
Home page

Comment (Some html is allowed: a@href@title, b, em, i, strike, strong, u) where the @ means "attribute." For example, you can use <a href="" title=""> or <blockquote cite="Scott">.  

Live Comment Preview

Search

Categories

On this page

Archive

Total Posts: 67
This Year: 0
This Month: 0
This Week: 0
Comments: 16