Wednesday, October 21, 2015

Add Two Numbers

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
思路:
1. 第一眼看到以为要先reverse,其实不需要。
2. 考虑两个链表只要有一个为空,就可以直接返回另一个。
3. 双指针分别指向两个链表,一步步做相加,直到其中有一个为空指针。考虑进位。
4. 此时分两种情况讨论
   a) 双指针同时为空,只需考虑进位大于0的情况,加入一个新的节点。
   b) 其中有一个指针为空,则另一个指针进入新的循环,直到另一个指针也为空时结束。
      结束前也需考虑如果进位大于0,则在末尾加入一个新的节点。

No comments:

Post a Comment