Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a understandable Doubly Linked List

I am trying to create a generic doubly linked list , and I am having trouble getting my head around it. Does anyone have an example of a very simple implementation of Doubly Linked List using C#?

Thanks

like image 899
Jaimenk_474 Avatar asked Feb 24 '23 17:02

Jaimenk_474


1 Answers

Below a simple generic double-linked list supporting Add(), an indexer and ToString() - the rest is left as an exercise for the reader - this should give you an idea.

public class LinkedList<T>
{
   protected LinkedListNode<T> root = null;
   protected LinkedListNode<T> last = null;
   public LinkedList()
   {
   }

   public string ToString()
   {
       StringBuilder sb = new StringBuilder();
       var node = root;
       while (node != null)
       {
           sb.Append("{ " + node.Data.ToString() + " } ");
           node = node.Next;
       }
       return sb.ToString();
   }

   public T this[int index]
   {
        get
        {
           var node = GetAt(index);
           if(node == null)
                throw new ArgumentOutOfRangeException();
           return node.Data;
        }
        set
        {
           var node = GetAt(index);
           if (node == null)
                throw new ArgumentOutOfRangeException();
           node.Data = value;
        }
   }

    private LinkedListNode<T> GetAt(int index)
    {
        var current = root;
        for(int i=0;i<index;i++)
        {
            if (current == null)
                return null;
            current = current.Next;
        }
        return current;
    }

    public void Add(T data)
    {
        if (root == null)
        {
            root = new LinkedListNode<T>(data);
            last = root;
        }
        else
        {
            last.Next = new LinkedListNode<T>(data);
            last.Next.Previous = last;
            last = last.Next;
        }
    }
}

public class LinkedListNode<T>
{
    public T Data {get;set;}

    public LinkedListNode(T data)
    {
        Data = data;
    }

    public LinkedListNode<T> Next { get; set; }
    public LinkedListNode<T> Previous { get; set; }
}
like image 152
BrokenGlass Avatar answered Mar 05 '23 15:03

BrokenGlass