2. 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
Solution
水题,复习数据结构
/**
* 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) {
int carry = 0;
ListNode* sum = new ListNode(-1);
ListNode* p_sum = sum;
ListNode* op1 = l1, *op2 = l2;
while (op1 && op2){
int newDigit = op1->val + op2->val + carry;
carry = newDigit / 10;
ListNode* newNode = new ListNode(newDigit%10);
p_sum->next = newNode;
p_sum = p_sum->next;
op1 = op1->next;
op2 = op2->next;
}
while(op1){
int newDigit = op1->val + carry;
carry = newDigit / 10;
ListNode* newNode = new ListNode(newDigit%10);
p_sum->next = newNode;
p_sum = p_sum->next;
op1 = op1->next;
}
while(op2){
int newDigit = op2->val + carry;
carry = newDigit / 10;
ListNode* newNode = new ListNode(newDigit%10);
p_sum->next = newNode;
p_sum = p_sum->next;
op2 = op2->next;
}
if (carry > 0){
ListNode* newNode = new ListNode(carry);
p_sum->next = newNode;
}
return sum->next;
}
};