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 后面。
Coding
/** * 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;};