Merge two sorted linked lists

Sort by

recency

|

42 Discussions

|

  • + 0 comments

    Java Solution

        static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) {
            
            
            SinglyLinkedListNode head = new SinglyLinkedListNode(0); 
            SinglyLinkedListNode temp = head; //temp head, use for traversal
            SinglyLinkedListNode node1 = head1;
            SinglyLinkedListNode node2 = head2;
            while(node1 != null && node2 != null){
                if(node1.data < node2.data){
                    temp.next = node1;
                    node1 = node1.next;
                }else{
                    temp.next = node2;
                    node2 = node2.next;
                }
                temp = temp.next;
            }
            
            if(node1 != null){
                temp.next = node1;
            }
            
            if(node2 != null){
                temp.next = node2;
            }
            
            return head.next;
        }
    
  • + 0 comments
    sys.setrecursionlimit(2000)
    
    def mergeLists(head1, head2):
        if not (head1 and head2):
            return head1 if head1 else head2
    
        if head1.data < head2.data:
            head1.next = mergeLists(head1.next, head2)
            return head1
        else:
            head2.next = mergeLists(head1, head2.next)
            return head2
    
  • + 0 comments

    Java 8 - Solution

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

    Here is Hackerrank merge two sorted linked lists problem solution in Python, Java, c++ c and javascript

  • + 0 comments

    java solution static SinglyLinkedListNode mergeLists(SinglyLinkedListNode head1, SinglyLinkedListNode head2) { List numbers = new ArrayList<>(); SinglyLinkedListNode h1 = head1; while(h1 != null){ numbers.add(h1.data); h1=h1.next; } SinglyLinkedListNode h2 = head2; while(h2 != null){ numbers.add(h2.data); h2=h2.next; } Collections.sort(numbers, Comparator.reverseOrder()); SinglyLinkedListNode h3 = new SinglyLinkedListNode(numbers.get(0)); for (int i=1;i