Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
这道题目使用recursion比较简单,因为recursion可以很简单的做到先处理后面的nodes再链接前面的nodes,即可以不让前面的nodes丢失后面的部分,而使用iteration就会复杂一些。
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
return self.merge(l1, l2)
def merge(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val <= l2.val:
# 先处理后面的,再拼接前面的
l1.next = self.merge(l1.next, l2)
return l1
else:
l2.next = self.merge(l1, l2.next)
return l2