Search for a command to run...
Traverse both lists side-by-side, picking the smaller node at each step to build the merged list
Initialization
dummyNode set up. Start comparing head nodes of both lists.
Two-Pointer Iterative Merge
1class Solution {2 mergeTwoLists(list1, list2) {3 let dummyNode = new ListNode(-1);4 let temp = dummyNode;5 6 while (list1 !== null && list2 !== null) {7 if (list1.val <= list2.val) {8 temp.next = list1;9 list1 = list1.next;10 } else {11 temp.next = list2;12 list2 = list2.next;13 }//i: 0j: 014 temp = temp.next;15 }16 17 if (list1 !== null) {18 temp.next = list1;19 } else {20 temp.next = list2;21 }22 23 return dummyNode.next;24 }25}