Esempio n. 1
0
        private static DoublyLinkedListNode sortedInsert(DoublyLinkedListNode head, int data)
        {
            var node = new DoublyLinkedListNode(data);

            if (head == null)
            {
                return(node);
            }

            if (data < head.data)
            {
                node.next = head;
                head.prev = node;
                return(node);
            }

            // RECUSIVE
            var n = sortedInsert(head.next, data);

            head.next = n;
            n.prev    = head;
            return(head);

            // MY ITERATIVE APPROACH
            //var cur = head;
            //while (cur.next.data < data)
            //{
            //    cur = cur.next;
            //    if (cur.next == null) break;
            //}

            //if (cur.next == null)
            //{
            //    node.prev = cur;
            //    cur.next = node;
            //}
            //else
            //{
            //    node.next = cur.next;
            //    node.prev = cur;
            //    cur.next = node;
            //}
            //return head;
        }
Esempio n. 2
0
        // link - https://www.hackerrank.com/challenges/insert-a-node-into-a-sorted-doubly-linked-list/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=linked-lists
        private static void Main(string[] args)
        {
            int t = Convert.ToInt32(Console.ReadLine());

            for (int tItr = 0; tItr < t; tItr++)
            {
                DoublyLinkedList llist = new DoublyLinkedList();

                int llistCount = Convert.ToInt32(Console.ReadLine());

                for (int i = 0; i < llistCount; i++)
                {
                    int llistItem = Convert.ToInt32(Console.ReadLine());
                    llist.InsertNode(llistItem);
                }

                int data = Convert.ToInt32(Console.ReadLine());

                DoublyLinkedListNode llist1 = sortedInsert(llist.head, data);

                PrintDoublyLinkedList(llist1, " ");
            }
        }
Esempio n. 3
0
 public DoublyLinkedListNode(int nodeData)
 {
     this.data = nodeData;
     this.next = null;
     this.prev = null;
 }
Esempio n. 4
0
 public DoublyLinkedList()
 {
     this.head = null;
     this.tail = null;
 }