Problem: 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

Solution: Add Two Numbers, 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
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
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Date : 2015-02-03 22:49:26
# @Author : NSSimacer
# @Version : 1.0
# 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):
digit_sum = ListNode(0)
carry_out = 0
s = digit_sum
while l1 or l2 or carry_out:
if l1:
s.val += l1.val
l1 = l1.next
if l2:
s.val += l2.val
l2 = l2.next
carry_out = s.val / 10
s.val = s.val % 10
if l1 or l2 or carry_out:
s.next = ListNode(carry_out)
s = s.next
return digit_sum

和大数相加思路相似,用一个变量保存进位值,对两个数的每一位分别计算和,进位值作为计算下一位和的初始值。只不过这里把数值存到链表里,需要增加一些对链表的操作。
时间复杂度O(M + N),空间复杂度O(1)。