Description of the original title:
You have two integers that are represented by a linked list, where each node contains a number. The numbers are stored in the order of the original integers 相反
so that the first number is at the beginning of the list. Write a function that adds two integers and returns the sum in the form of a list.
Have you ever encountered this problem in a real interview? Yes
Sample Example
Give two linked lists 3->1->5->null
and 5->9->2->null
, return8->0->8->null
labelCracking The Coding interview chain table high accuracy
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Nonec Lass Solution: # @param l1:the first list # @param l2:the second list # @return: The sum list of L1 and l2
def addlists (self, L1, L2): # Write your code here
Topic Analysis:
函数addLists,入参为两个链表,长度无限制,即可能存在长度:list1 > list2; list1 = list2; list1 < list2;
The final linked list length is based on the longest linked list length n, which returns the list length (n~n+1)
# Definition for singly-linked list.# class listnode:# def __init__ (self, x): # self.val = x# Self.next = Noneclass Solution: # @param l1:the First list # @param l2:the second List # @return: The sum list of L1 and L2 def addlists (self, L1, L2): # Write your code here if L1 are None:return L2 if L2 is None:re Turn L1 head1 = L1 head2 = L2 flag = 0 While head1.next are not None or HEAD2.N Ext is not None: # The existence of a linked list when next is empty, constructs Next.val = 0, does not affect the addition result if Head1.next is none:head1. Next = ListNode (0) If head2.next is None:head2.next = ListNode (0) Su Mnum = Head1.val + head2.val if sumnum >= 10:head1.val = sumnum%10 flag = 1 Head1.next.val + = 1 Else:head1.val = Sumnum flag = 0 He AD1 = Head1.next Head2 = Head2.next Else: # When the end of the list is processed separately, and is greater than 10 o'clock, append node Head1.val = head1.val + head2.val If head1.val >= 10:head1.val = head1.val%10 Head1.next = ListNode (1) retur n L1
Lintcode Python Simple-level topic list summation