Пример #1
0
        public Node sortedMerge_leetcode(Merge2SortedList_ExtraSpace.Node h1, Merge2SortedList_ExtraSpace.Node h2)
        {
            //add dummy node
            Node dummy = new Node(0);
            //pointer pointing to the dummy node
            Node tail = dummy;

            while (h1 != null && h2 != null)
            {
                if (h1.data < h2.data)
                {
                    dummy.next = h1;
                    h1         = h1.next;
                }
                else
                {
                    dummy.next = h2;
                    h2         = h2.next;
                }
                dummy = dummy.next;
            }
            if (h1 != null)
            {
                dummy.next = h1;
            }
            else
            {
                dummy.next = h2;
            }
            //because head is saving the reference
            return(head.next);
        }
Пример #2
0
        //we are not told tat list contains negative numbers or not

        public Node sortedMerge(Merge2SortedList_ExtraSpace.Node h1, Merge2SortedList_ExtraSpace.Node h2)
        {
            //add dummy node
            Node dummy = new Node(0);
            //pointer pointing to the dummy node
            Node tail = dummy;

            while (true)
            {
                if (h1 == null)
                {
                    tail.next = h2;
                    break;
                }
                if (h2 == null)
                {
                    tail.next = h1;
                    break;
                }

                if (h1.data <= h2.data)
                {
                    tail.next = h1;
                    h1        = h1.next;
                }
                else
                {
                    tail.next = h2;
                    h2        = h2.next;
                }
                tail = tail.next;
            }
            return(dummy.next);
        }