First, the topic
You are given, linked lists representing, and non-negative numbers. The digits is stored in reverse order and all of their nodes contain a single digit. ADD the numbers and return it as a linked list.
Input: (2, 4, 3) + (5, 6, 4)
Output:7, 0, 8
Second, the analysis
The problem is the large number of additions, and Python does not have to consider data type problems. In addition to the reverse order also does not have any impact, input reverse, output is reverse order, directly from 0 to start.
Third, the realization of ideas
1. Create a linked list as the final output result
2. Remove the number of the l1,l2 in the same position, and add the tempsum with the rounding. % as the standard value thisvalue,/as the next digit carry Nextextra
3. Flocculent and the process of L1 or L2 is none, it means that the list has been to the end, plus and 0 as a substitute.
Four, difficulties
The exit condition of the 1.while loop needs to be considered in the overall order to determine the three items: L1,l2 and Nextextra
2.Python Linked list operation
Five, Python code
1# Definition forsingly-linked list.2#classListNode:3 # def __init__ (self, x):4# self.val =x5# Self.next =None6 7 classSolution:8 # @param {listnode} L19 # @param {ListNode} L2Ten # @return {ListNode} One def addtwonumbers (self, L1, L2): Alinklist = P = ListNode (0) -Nextextra =0 - the whileL1 or L2 or Nextextra: - ifL1: -Temp1 =L1.val - Else: +Temp1 =0 - + ifL2: ATemp2 =L2.val at Else: -Temp2 =0 - -TempSum = Temp1 + Temp2 +Nextextra -Thisvalue = tempsum%Ten -Nextextra = tempsum/Ten in -P.next =ListNode (Thisvalue) top =P.next + ifL1: -L1 =L1.next the ifL2: *L2 =L2.next $ Panax Notoginseng returnLinklist.next
Vi. Summary
1. In this case, learn about the methods of the list in Python. Using class to define a data type is better than the C language, and the L1,L2 in the code are pointers, without * Making the code look very concise.
2. Linked list Continuous declaration linklist = P = ListNode (), here p,linklist is to represent a linked list, but here p is used to perform a backward shift to add elements, linklist always point to the beginning of the list. It's the use of pointers, but it feels good to use.
3. Before using the C language to achieve the large number of add, to convert int to Str. One of the first reactions to this question was to convert to STR, which was misled for a moment, after looking at someone else's code before returning to God.
4. Inefficient, executed 202ms, ranked in the middle, and students to discuss where to optimize.
5. Sometimes the fastest algorithms are often based on the specific requirements of the design of the "trickery" algorithm, this aspect also needs to exercise, specific analysis of concrete problems, to obtain the best results, there should be a long way to go.
6. No, come on!
#2 ADD Numbers