Merge two sorted linked lists

Sort by

recency

|

209 Discussions

|

  • + 0 comments

    There is no Go template...

  • + 0 comments

    Hi, solution using Java:

    static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            SinglyLinkedListNode head = new SinglyLinkedListNode(-1);
            SinglyLinkedListNode curr = head;
            
            if (head1 == null) return head2;
            if (head2 == null) return head1;
            
            while (head1 != null && head2 != null) {
                if (head1.data < head2.data) {
                    curr.next = head1;
                    head1 = head1.next;
                } else {
                    curr.next = head2;
                    head2 = head2.next;
                }
                
                curr = curr.next;
            }
            
            if (head1 == null) {
                curr.next = head2;
            } else {
                curr.next = head1;
            }
            
            return head.next;
        }
    
  • + 0 comments

    How is this question still broken for so many languages months after people have been commenting about it?? Frustrating that most of the languages "available" aren't able to be used for this without some serious additions

  • + 0 comments

    Python3. Hope they don't mind me reusing their list class :P

    def mergeLists(
        head_1: SinglyLinkedListNode | None,
        head_2: SinglyLinkedListNode | None
    ) -> SinglyLinkedListNode | None:
        merged = SinglyLinkedList()
        
        while head_1 or head_2:
            min_head = min(
                (head_1, head_2),
                key=lambda head: head.data if head else float('inf')
            )
            
            merged.insert_node(min_head.data)
            
            # iterate the source list
            if min_head == head_1:
                head_1 = head_1.next
            else:
                head_2 = head_2.next
                
        return merged.head
    
  • + 0 comments

    In c++20 the template is empty