You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.

Example:

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

思路

这道题目可以采用简单的链表操作来搞定。题目说要求不能反转链表,这样无形中就会增加我们算法的复杂度。

我们采用竖式加法运算操作,

1
2
3
7 2 4 3
+ 5 6 4
= 7 8 0 7

我们首先可以遍历一遍得到链表的长度。再进行O(n^2)的操作,多次遍历单链表,从个位开始,从后往前进行加法运算。注意进位即可。

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
length1 = 0
length2 = 0
l1cur = l1
l2cur = l2
while(l1cur.next):
length1 += 1
l1cur = l1cur.next
while(l2cur.next):
length2 += 1
l2cur = l2cur.next
res = []
carry = 0
l1val = l1cur.val
l2val = l2cur.val
while(length1 >= 0 or length2 >= 0):
tmpsum = l1val + l2val + carry
if tmpsum >= 10:
tmpsum = tmpsum - 10
carry = 1
else:
carry = 0
cur = ListNode(tmpsum)
res.append(cur)
l1cur = l1
l2cur = l2
if length1 > 0:
for i in range(length1-1):
l1cur = l1cur.next
l1val = l1cur.val
else:
l1val = 0
if length2 > 0:
for i in range(length2-1):
l2cur = l2cur.next
l2val = l2cur.val
else:
l2val = 0
length1 -= 1
length2 -= 1
if (carry):
cur = ListNode(carry)
res.append(cur)
length = len(res)
if (length == 0):
return None
elif (length == 1):
return res[0]
else:
head = res[-1]
for i in range(length-1, 0, -1):
res[i].next = res[i-1]
return head