A doubly-linked list is a linked data structure that consists of a set of sequentially linked records called nodes. Each node contains two fields, called links, that are references to the previous and to the next node in the sequence of nodes. The beginning and ending nodes’ previous and next links, respectively, point to some kind of terminator, typically a sentinel node or null, to facilitate traversal of the list. If there is only one sentinel node, then the list is circularly linked via the sentinel node. It can be conceptualized as two singly linked lists formed from the same data items, but in opposite sequential orders.

image_thumb3

Source : http://en.wikipedia.org/wiki/Doubly-linked_list

Code

    public class DoubleLinkList<T>
    {
        private DoubleNode<T> head;
        private DoubleNode<T> tail;

        public int InsertAtHead(DoubleNode<T> item)
        {

            if (head == null)
            {
                item.Next = item.Previous = null;
                head = item;
                tail = item;
                return 0;
            }

            head.Previous = item;
            item.Next = head;
            head = item;

            return 0;
        }
        
        public int InsertAtTail(DoubleNode<T> item)
        {
            if (head == null)
            {
                item.Next = item.Previous = null;
                head = item;
                tail = item;
                return 0;
            }

            tail.Next = item;
            item.Previous = tail;
            tail = item;
            return 0;
        }

        public void ShowFromHead()
        {
            var temp = head;
            while (temp != null)
            {
                Console.Write(temp.Data + "->");
                temp = temp.Next;
            }
            Console.WriteLine(Environment.NewLine);
        }

        public void ShowFromHead(DoubleNode<T> root)
        {
            var temp = root;
            while (temp != null)
            {
                Console.Write(temp.Data + "->");
                temp = temp.Next;
            }
            Console.WriteLine(Environment.NewLine);
        }

        public void ShowFromTail()
        {
            var temp = tail;
            while (temp != null)
            {
                Console.Write(temp.Data + "->");
                temp = temp.Previous;
            }
            Console.WriteLine(Environment.NewLine);
        }
    }

    public class DoubleNode<T>
    {
        public DoubleNode<T> Next { get; set; }
        public DoubleNode<T> Previous { get; set; }
        public T Data { get; set; }

    }