[LeetCode]21. 合并两个有序链表(Merge Two Sorted Lists)

题目描述

将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

示例:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4

解题思路

类似于归并排序。

代码

Python 3.6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None

class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if l1 is None:
return l2
if l2 is None:
return l1
dummy = ListNode(-1)
cur = dummy
cur1, cur2 = l1, l2
while cur1 is not None and cur2 is not None:
if cur1.val <= cur2.val:
cur.next = ListNode(cur1.val)
cur1 = cur1.next
else:
cur.next = ListNode(cur2.val)
cur2 = cur2.next
cur = cur.next
if cur1 is not None:
cur.next = cur1
if cur2 is not None:
cur.next = cur2
return dummy.next

执行用时 : 64 ms
内存消耗 : 13.8 MB