Leetcode
2.Add Two Numbers
题目描述
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.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
算法代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* l = ( ListNode* ) malloc ( sizeof(ListNode) );
l -> next = NULL;
ListNode* first = l;
int num = 0;
int cnt = 1;
while( l1 != NULL || l2 != NULL){
if( l1 != NULL ){
num = num + l1 -> val;
}
if( l2 != NULL){
num = num + l2 -> val;
}
l -> val = num % 10;
if( l1 != NULL){
l1 = l1 -> next;
}
if( l2 != NULL ){
l2 = l2 -> next;
}
if( l1 != NULL || l2 != NULL ){
l -> next = ( ListNode* ) malloc ( sizeof(ListNode) );
l = l -> next;
l -> next = NULL;//若指针不指向 NULL 又没有明确指向的话会报错
}
//注意进位
if( num >= 10){
num = 1;
} else {
num = 0;
}
}
if( num == 1){
l -> next = ( ListNode* ) malloc ( sizeof(ListNode) );
l = l -> next;
l -> next = NULL;
l -> val = 1;
}
return first;
}
};
解题思路
首先注意审题,题目给的是倒序(reverse),先个位后十位再是百位这样的顺序。其次是进位问题,如果发生进位,链表的下一项值需要加一。两个列表的长度也不一定是相等的,可能是 100 + 1这种形式。有人可能会先把数存起来,再用取余和除法构建链表(我一开始就是这么做的)但是这样可能会造成数值的溢出,并且效率不如直接算一位存一位。最后是指针开辟问题,如果 next 不指向空也不指向特定空间的话运行是会报错的,需要注意。