Merge two sorted listed
Merge two sorted linked lists and return is as a sorted list. The list should be made by splicing together the nodes of the first two lists.
自己出错的地方:
(1)定义的result=LinkNode()
那初始值有一个0,返回的时候要用的是:result.next
就是result.next所指向的所有的后续。
(2)要定义一个可以移动的指针cur,因为result是不能变化的。最开始忘记了。
(3)==和=,在写条件的时候总是忽略。不是不会,就是没养成习惯。
1 循环迭代法
# 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:
result=ListNode()
cur=result
if l1==None and l2==None:
return result.next
while l1!=None or l2!=None:
if l1==None:
while l2!=None:
cur.next=ListNode(l2.val)
l2=l2.next
cur=cur.next
return result.next
if l2==None:
while l1!=None:
cur.next=ListNode(l1.val)
l1=l1.next
cur=cur.next
return result.next
if l1.val<=l2.val:
cur.next=ListNode(l1.val)
l1=l1.next
cur=cur.next
else:
cur.next=ListNode(l2.val)
l2=l2.next
cur=cur.next
return result.next
循环迭代法2
# 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:
result=ListNode()
cur=result
while (l1!=None and l2!=None):
if l1.val<=l2.val:
cur.next=l1
l1=l1.next
else:
cur.next=l2
l2=l2.next
cur=cur.next
cur.next=l1 or l2
return result.next
第二个要比第一个写的好
(1)cur.next=l1 or l2 这个之前我不会写。
意思是若全是l1,则l1全部放到result中。
若全是l2,则l2全部放到result中。
这只需要把指针指过去就可以。关于链表的这一点,还没有理解。
(2)返回值:result.next而不是result。这个我一直没有搞懂。
题目里面是没有result节点的,所以要返回的是result.next指向的地方。
(3)time complexity 因为遍历 O(n)
space complexity 因为不知道需要多少空间,需要l1+l2个元素的总量。因为是O(n)
2 递归法
# 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==None or l2==None:
return l1 or 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
(1)要先考虑递归终止条件
(2)这个递归比较绕,需要一点一点回推。不是很懂,其实是对递归的过程不是很理解