赞
踩
思路1:递归
思路2:额外列表排序
思路3:常规遍历
思路1代码:
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode: if not pHead1: # pHead1为None时将pHead2整体返回 return pHead2 if not pHead2: # pHead2为None时将pHead1整体返回 return pHead1 if pHead1.val <= pHead2.val: # 值小的在前,后面指向第二小的值即可 pHead1.next = self.Merge(pHead1.next,pHead2) return pHead1 # 将比较得到的小值返回 else: pHead2.next = self.Merge(pHead1,pHead2.next) return pHead2 # write code here
思路2代码:
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode: if not pHead1: return pHead2 if not pHead2: return pHead1 node_list = [] while pHead1: node_list.append(pHead1) pHead1 = pHead1.next while pHead2: node_list.append(pHead2) pHead2 = pHead2.next node_list.sort(key=lambda x:x.val) pHead = index = node_list[0] for item in node_list[1:]: index.next = item index = index.next return pHead # write code here
思路3代码:
# class ListNode: # def __init__(self, x): # self.val = x # self.next = None # # 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 # # # @param pHead1 ListNode类 # @param pHead2 ListNode类 # @return ListNode类 # class Solution: def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode: if not pHead1: return pHead2 if not pHead2: return pHead1 pHead = index = ListNode(-1) while pHead1 and pHead2: if pHead1.val <= pHead2.val: index.next = pHead1 pHead1 = pHead1.next else: index.next = pHead2 pHead2 = pHead2.next index = index.next if pHead1: index.next = pHead1 else: index.next = pHead2 return pHead.next # write code here
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。