You are given two linked lists representing two non-negative numbers. 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:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 8 -> 0 -> 7
解法1:Reverse + 两数相加
因为list的头是最高位,我们要相加是从最低位开始加,所以如果能先反转的话比较容易做。分别reverse再求和,最后把结果list再reverse一下就可以了。
C++
Java
解法2: Follow up O(N) Time and Space
从list的最后加,如果不能反转,需要想到有一种数据结构是可以从后往前存储的,那就是stack。
用两个stack保存每一个队列的node,然后往回加。
C++