题目要求
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
思路一
遍历2个链表,按大小顺序构建一个新的有序链表
→_→ talk is cheap, show me the code
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
p, q = l1, l2
m = n = ListNode(0)
while p and q:
if p.val <= q.val:
n.next = p
p = p.next
else:
n.next = q
q = q.next
n = n.next
n.next = q or p
return m.next