合并两个有序链表
题目:
将两个有序链表合并为一个新的有序链表并返回。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
方法一:迭代
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
currentNode = tempNode = ListNode(0)
if not l1 and not l2:
return None
while l1 and l2:
if l1.val <= l2.val:
currentNode.next = l1
l1 = l1.next
else:
currentNode.next = l2
l2 = l2.next
currentNode = currentNode.next
if l1 or l2:
currentNode.next = l1 or l2
return tempNode.next
ListNode(0)这个是什么意思?
刚开始我也懵,仔细看了下。发现这是个实例化的东西。LeetCode题目前面有个ListNode的类的定义,初始化时需要传进去一个值。
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
我们做题目时,其实没有用到这个实例化的值,也就是说ListNode括号里面的0,也可以是100,20,3这些,我们实际不会用到,我们最后返回的是(return tempNode.next)这个节点以后的那些节点。
方法一是没有动原来的l1和l2链表,重新搞了一个新链表放这个排序,而链表嘛,首先要有个头不是嘛,ListNode(0)就是新建了一个头,后面自己加节点,自己玩儿去~ 反正最后这个头不跟你们走~
涨姿势的写法:currentNode.next = l1 or l2
if l1 or l2:
currentNode.next = l1 or l2
这种写法没见过。自己先测试一下:
>>> a = [1,2,3]
>>> b = []
>>> if a or b:
... print(a or b)
...
[1, 2, 3]
发现这个是真的,记下来哦,不要再傻傻的用if…else了。
方法一:迭代(简化)
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
currentNode = tempNode = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
currentNode.next = l1
l1 = l1.next
else:
currentNode.next = l2
l2 = l2.next
currentNode = currentNode.next
currentNode.next = l1 or l2
return tempNode.next
无意中看到一个更简洁的版本,本着少写一行是一行的原则(因为懒),可以将方法一的代码简化一下。
如果l1l2都不存在,直接return tempNode.next,而tempNode.next就是为空的。下面的代码就会出现重复,去掉吧。
if not l1 and not l2:
return None
还有,将下面的代码
if l1 or l2:
currentNode.next = l1 or l2
替换为:
currentNode.next = l1 or l2
是不是很简单,少写了三行代码哦~
方法二:递归
class Solution(object):
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 or not l2:
return l1 or l2
while l1 and l2:
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2