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
从整体上来讲是一个不太难的链表题,主要是要细心,考虑到各种情况。由于一个数是倒叙按位存放在链表当中,所以更加方便了存取和计算进位。总体而言,就是使用两个临时指针按顺序一个节点一个节点往下走,每个节点计算两数之和已经进位,然后带进下一个节点的计算当中。但是由于ListNode里面并没有定义size或功能类似的变量,所以我们无法直接获得链表了l1和l2 的长度,否则便可以直接定义l1为较长的链表而l2为较短的链表,从而使得计算更为简单。
所以我们只能选择分情况考虑了。若是l1和l2恰巧等长,那自然是最好的,但我们也要考虑到更为常见的不等长的情况。当链表l1的长度比l2长时,运算到后面的时候,会遇到l2已经为空了但l1依旧有值,此时输出result的值应为l1节点中存放的值(+进位),l2已经到顶了,再往下找节点会导致越界。l2比l1长的时候同理。
但这里不要忘了一个问题,最高位还是