July 28, 2017

An Alternative Queue Class

Here is an alternative generic Queue class. I created it as I constantly found when using a queue class that Enqueue and Dequeue were never enough. There was always a need for a remove an item and a need to iterate through all the items in a queue. The original basic source for the queue class is here.
public class Node< T >
{
    public T Data { get; set; }
    public Node<T> Next { get; set; }

    public Node( T data )
    {
        this.Data = data;
    }
}

public class Queue2< T >
{
    private Node<T> _head;
    private Node<T> _tail;
    private int _count;
    private readonly IEqualityComparer<T> _comparator;

    public Queue2()
    {
        _comparator = EqualityComparer<T>.Default;
    }

    public Queue2( IEqualityComparer<T> comparator )
    {
        _comparator = comparator;
    }

    public void Enqueue(
        T data )
    {
        Node<T> _newNode = new Node<T>( data );
        if ( _head == null )
        {
            _head = _newNode;
            _tail = _head;
        }
        else
        {
            _tail.Next = _newNode;
            _tail = _tail.Next;
        }
        ++_count;
    }

    public T Dequeue()
    {
        if ( _head == null )
        {
            throw new Exception( "Queue is Empty" );
        }
        T _result = _head.Data;
        _head = _head.Next;
        --_count;
        return _result;
    }

    public void Remove(
        T item )
    {
        Node<T> previous = null, cursor = _head;
        bool found = false;
        while ( ( cursor != null ) && !found )
        {
            found = _comparator.Equals( cursor.Data, item );
            if ( found )
            {
                if ( previous == null )
                {
                    _head = cursor.Next;
                }
                else
                {
                    previous.Next = cursor.Next;
                }
                --count;
            }
            else
            {
                previous = cursor;
                cursor = cursor.Next;
            }
        }
    }

    public void Clear()
    {
        _head = _tail = null;
        count = 0;
    }

    public IEnumerable<T> GetEnumerator()
    {
        Node<T> cursor = _head;
        while ( cursor != null )
        {
            yield return cursor.Data;
            cursor = cursor.Next;
        }
    }

    public int Count
    {
        get { return this._count; }
    }
}

No comments: