Merge two sorted linked lists

  • + 0 comments

    C#

        static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2)
        {
            if (head1 == null) return head2;
            if (head2 == null) return head1;
            SinglyLinkedListNode head;
            if (head1.data <= head2.data)
            {
                head = head1;
                head1 = head1.next;
            }
            else
            {
                head = head2;
                head2 = head2.next;
            }
            head.next = mergeLists(head1, head2);
            return head;
        }