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.
解法一:
O(max(n,m)):从两个链表的表头开始,计算两个链表当前元素和进位位的和,并且将结果分成当前结果和进位结果,直到两个链表指针移动到表尾,判断进位位是否为0,若不为0,则需要再添加一位数字表示最终的进位。
/**
* 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 *p = l1,*q = l2;
ListNode *res = (ListNode *)malloc(sizeof(ListNode));
ListNode *newp = res;
int carry = 0,result = 0,sum = 0;
while(p != nullptr && q != nullptr)
{
sum = p->val + q->val + carry;
carry = sum/10;
result = sum%10;
ListNode *temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = result;
temp->next = nullptr;
newp->next = temp;
newp = temp;
p = p->next;
q = q->next;
}
while(p!=nullptr)
{
sum = p->val + carry;
carry = sum/10;
result = sum%10;
ListNode *temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = result;
temp->next = nullptr;
newp->next = temp;
newp = temp;
p = p->next;
}
while(q!=nullptr)
{
sum = q->val + carry;
carry = sum/10;
result = sum%10;
ListNode *temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = result;
temp->next = nullptr;
newp->next = temp;
newp = temp;
q = q->next;
}
if(carry != 0)
{
ListNode *temp = (ListNode *)malloc(sizeof(ListNode));
temp->val = carry;
temp->next = nullptr;
newp->next = temp;
newp = temp;
}
return res->next;
}
};