23 April 2024
Easy
21. Merge Two Sorted Lists
Link: https://leetcode.com/problems/merge-two-sorted-lists
Description: Given two sorted linked lists, merge them into a single sorted linked list and return it.
Solution:
Create a new linked list with a dummy node. Traverse both linked lists and compare the values of the nodes. Add the smaller node to the new linked list and move the pointer of the smaller node to the next node. Update the current pointer of the new linked list to the next node. Repeat the process until one of the linked lists reaches the end. Add the remaining nodes of the other linked list to the new linked list. Return the next node of the dummy node.
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} list1
* @param {ListNode} list2
* @return {ListNode}
*/
var mergeTwoLists = function (list1, list2) {
let res = new ListNode(-1)
let current = res
while (list1 !== null && list2 !== null) {
if (list1.val < list2.val) {
current.next = list1
list1 = list1.next
} else {
current.next = list2
list2 = list2.next
}
current = current.next
}
if (list1 !== null) {
current.next = list1
} else if (list2 !== null) {
current.next = list2
}
return res.next
}