21. 合并两个有序链表
题目来源:21. 合并两个有序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
/** * Definition for singly-linked list. * function ListNode(val, next) { * this.val = (val===undefined ? 0 : val) * this.next = (next===undefined ? null : next) * } */ /** * @param {ListNode} l1 * @param {ListNode} l2 * @return {ListNode} */ var mergeTwoLists = function(l1, l2) { let fir = l1; let sec = l2; let res = null; let tail = null; while(fir != null && sec != null){ let cur = null; if(fir.val <= sec.val){ cur = fir; fir = fir.next; }else{ cur = sec; sec = sec.next; } if(res == null){ res = cur; tail = res; }else{ tail.next = cur; tail = cur; } } let next = (fir == null)?sec:fir; if(tail == null){ res = next; }else{ tail.next = next; } return res; };
提示:
- 两个链表的节点数目范围是
[0, 50]
-100 <= Node.val <= 100
l1
和l2
均按 非递减顺序 排列
Python3
# Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if l1 is None: return l2 elif l2 is None: return l1 elif l1.val < l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2 class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: preHead = ListNode(-1) pre = preHead while l1 and l2: if l1.val < l2.val: pre.next = l1 l1 = l1.next else: pre.next = l2 l2 = l2.next pre = pre.next pre.next = l1 if l1 is not None else l2 return preHead.next