DEV Community

ZeeshanAli-0704
ZeeshanAli-0704

Posted on

Merge Two Sorted Linked List - I

Merging two Linked List

Approach 1 (Naive)

Getting items from both list, sorting them & forming linked list again.

var mergeTwoLists = function(list1, list2) {
    let array = [];
    let current = list1;
    while(current){
        array.push(current.val);
        current = current.next;
    }

    current = list2;
    while(current){
        array.push(current.val);
        current = current.next;
    };

    array = array.sort((a,b) => a-b);

    let head = null;

     const insertAtLast = (data) => {
      if (head === null) {
        head = new ListNode(data);
      } else {
        let current = head;
        while (current.next) {
          current = current.next;
        }
        current.next = new ListNode(data);
      }
    };

    for (let i = 0; i < array.length; i++) {
      insertAtLast(array[i]);
    }

    return head;


};

Enter fullscreen mode Exit fullscreen mode

Approach 2

Using two pointer & new List, Using comparison of values & generating new list

var mergeTwoLists = function(list1, list2) {
    let newNode = new ListNode(null,null);
    let listTail =newNode
    let listPointer1 = list1;
    let listPointer2 = list2;


    while(listPointer1 || listPointer2){

         if (!listPointer1) {
            listTail.next = listPointer2;
            break;
        } 
        if (!listPointer2) {
            listTail.next = listPointer1;
            break;
        }

        if(listPointer1.val > listPointer2.val){
            listTail.next = listPointer2;
            listPointer2 = listPointer2.next; 
        }else{
             listTail.next = listPointer1;
            listPointer1 = listPointer1.next; 
        }

        listTail= listTail.next;
    }
    return newNode.next;
};

Enter fullscreen mode Exit fullscreen mode

Top comments (0)