第四题啥都不想说…Add Two Numbers

我说这个题目感觉有问题…原来是自己没好好读题…
是说用两个链表表示两个非负数,每一位是逆向存储的…我就不说我理解成啥了…

Add Two Numbers

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

View Code PYTHON
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
 
class Solution:
    # @return a ListNode
    def addTwoNumbers(self, l1, l2):
    	Header = ListNode(0)
    	Last = Header
    	flag = 0
    	while flag or l1 or l2:
    		newNode = ListNode(flag)
    		if l1:
    			newNode.val += l1.val
    			l1 = l1.next
    		if l2:
    			newNode.val += l2.val
    			l2 = l2.next
    		flag = newNode.val / 10
    		newNode.val %=10
    		Last.next = newNode
    		Last = newNode
    	return Header.next

 

Share This: 

Leave a Reply

Your email address will not be published. Required fields are marked *