今天要讲的是一道经典的算法题,虽然不难,但是很有意思,我们一起来看下题目:
You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
翻译
给定两个非空的链表,代表两个非负整数。这两个整数都是倒叙存储,要求返回一个链表,表示这两个整数的和。
样例
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
解答
题目不难理解,思路也很容易想明白,其实就是模拟小学生打竖式计算加减的方法,来计算两个整数的加和。但是既然是加法,就可能涉及进位,比如两个两位数的和可能是一个三位数。还有一个难点是需要使用链表来实现,涉及链表,编码的复杂度会更大一些。
在开始编码之前,我们先仔细观察样例: