当前位置:网站首页>[leetcode] sum of two numbers II

[leetcode] sum of two numbers II

2022-06-23 03:38:00 LawsonAbs

1 subject

2 thought

Turn over the linked list before calculating , Then flip the linked list . This question requires that you be familiar with the operation of flipping the linked list .

3 Code

# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        l1 = self.reverseLinkList(l1)
        l2 = self.reverseLinkList(l2)
        head_l1 = l1
        #  Perform addition 
        flag = 0
        head = None
        while(l1 and l2):
            flag ,l1.val = divmod(l1.val + l2.val + flag,10)            
            head = l1
            l1 = l1.next
            l2 = l2.next
        
        if l2:
            l1 = l2
            head.next = l1
        while(l1):
            flag,l1.val = divmod(l1.val+flag,10)
            head = l1
            l1 = l1.next
        
        #  If there's a carry at the end 
        if flag :
            head.next = ListNode(flag,None)
        return self.reverseLinkList(head_l1)
        
    #  Flip list 
    def reverseLinkList(self,head):
        #  Flip in place 
        nxt = head.next
        pre = None
        while(head and nxt):
            tmp = nxt.next 
            head.next = pre #  modify 
            nxt.next = head
            pre = head
            head = nxt
            nxt = tmp
        return head #  Returns the flipped linked list 
原网站

版权声明
本文为[LawsonAbs]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206222218012960.html