You are given the heads of two sorted linked lists list1
and list2
.
Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.
Return the head of the merged linked list.
給兩定兩個 Linked-list list1
和 list2
將兩個 linked-list 合併,創建 res
,比較 list1 和 list2 的 value 誰比較大,將比較小的 linked-list 接在 res 後面。
/**
* 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, null);
let cur = res;
while (list1 && list2) {
if (list1.val > list2.val) {
cur.next = list2;
list2 = list2.next;
} else {
cur.next = list1;
list1 = list1.next;
}
cur = cur.next;
}
cur.next = list1 || list2;
return res.next;
};