/*
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.
5
5
01
1
99
001
9
999
8001
*/
/*
**
* 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* k = new ListNode(0);
ListNode* q = k;
int i = 0;
while(l1 != NULL || l2 != NULL){
int x = (l1 != NULL) ? l1->val : 0;
int y = (l2 != NULL) ? l2->val : 0;
int j = x + y + i;
i = j/10;
k->next = new ListNode(j%10);
k = k->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
if(i > 0){
ListNode* p = new ListNode(i);
k->next = p;
}
return q->next;
}
};
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//最终的优化程序 ,需要创建新的结点,C++ 创建新结点的方法和C稍有区别
//C++用new关键字来开辟空间,C语言用 malloc() 函数开辟内存空间
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* k = new ListNode(0);
ListNode* q = k;
int i = 0;
while(l1 != NULL || l2 != NULL || i){
int j = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + i;
i = j/10;
k->next = new ListNode(j%10);
k = k->next;
if(l1) l1 = l1->next;
if(l2) l2 = l2->next;
}
return q->next;
}
};