[LeetCode] Add Two Numbers

来源:互联网 发布:如何优化dnf非常流畅 编辑:程序博客网 时间:2024/06/15 01:39
[Problem]

You are given two linked lists representing two non-negativenumbers. The digits are stored in reverse order and each of theirnodes contain a single digit. Add the two numbers and return it asa linked list.

Input: (2 ->4 -> 3) + (5 -> 6 ->4)
Output: 7 -> 0 -> 8


[Analysis]
简单题,类似于两个排序链表的合并,注意最后的进位。

[Solution]

class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode *res = NULL;
ListNode *p = NULL;
int sum = 0, add = 0;
while(true){
// end
if(l1 == NULL && l2 == NULL){
break;
}

// add two list
sum = add;
if(l1 != NULL){
sum += l1 -> val;
l1 = l1 -> next;
}
if(l2 != NULL){
sum += l2 -> val;
l2 = l2 -> next;
}
add = sum / 10;
sum = sum % 10;
ListNode *node = new ListNode(sum);

// append to result
if(res == NULL){
res = node;
}
else{
p = res;
while(p -> next != NULL){
p = p -> next;
}
p -> next = node;
}
}

// be careful the last carry
if(add > 0){
ListNode *node = new ListNode(add);

// append to result
if(res == NULL){
res = node;
}
else{
p = res;
while(p -> next != NULL){
p = p -> next;
}
p -> next = node;
}
}
return res;
}
};


说明:版权所有,转载请注明出处。Coder007的博客
原创粉丝点击