链表专题训练
作者:互联网
1、合并两个有序链表
递归:判断两个节点值大小并递归下一次,递归出口为当节点为空时
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
if not list1:
return list2
if not list2:
return list1
if list1.val<list2.val:
list1.next=self.mergeTwoLists(list1.next,list2)
return list1
if list1.val>list2.val:
list2.next=self.mergeTwoLists(list2.next,list1)
return list2
2、两数相加
class Solution:
def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
pre = ListNode(-1)
curr = pre
carry = 0
while(l1 != None or l2 != None):
x = 0 if l1 == None else l1.val
y = 0 if l2 == None else l2.val
_sum = int(x + y + carry)
carry = 1 if _sum > 9 else 0
_sum = _sum % 10
curr.next = ListNode(_sum)
curr = curr.next
if l1 != None:
l1 = l1.next
if l2 != None:
l2 = l2.next
if carry == 1:
curr.next = ListNode(1)
return pre.next
标签:None,专题,ListNode,训练,next,链表,l2,l1,Optional 来源: https://www.cnblogs.com/feiyuyu/p/16512855.html