【leetcode - 21】合并升序链表
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
1. 考虑递归,如果遍历的时候,l1节点值小于l2,则返回的应该为此时的l1节点及l1.next和l2拼接后的结果,这就形成了递归的条件:
# 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 not l1: return l2 if not l2: return l1 if l1.val<=l2.val: #将l1的next指向剩下的合并后的结果 l1.next = self.mergeTwoLists(l1.next,l2) return l1 else: l2.next = self.mergeTwoLists(l1,l2.next) return l2
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 not l1: return l2 if not l2: return l1 #初始化 head = new = ListNode(None) while l1 and l2: l1val = l1.val l2val = l2.val if l1val<=l2val: head.next = ListNode(l1val) l1 = l1.next else: head.next = ListNode(l2val) l2 = l2.next head = head.next
#重点在下面,如果跳出while说明l1,l2中存在None了,直接拼接剩下的链表就好了 head.next = l1 if l1 else l2 return new.next
浙公网安备 33010602011771号