题目链接:https://leetcode.com/problems/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
思路
链表相加,要注意最后的进位,就是如果链表都加完了,进位标记仍为1,则还需要加一个结点。
/**
* 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) {
if(! l1) return l2;
if(! l2) return l1;
ListNode *head = new ListNode(0),*p = head;
int carry = 0;
while(l1 || l2){
int sum = 0,val;
if(l1) sum += l1->val,l1 = l1->next;
if(l2) sum += l2->val,l2 = l2->next;
val = (sum + carry) % 10,carry = (sum + carry) / 10;
ListNode *node = new ListNode(val);
p->next = node,p = p->next;
}
if(carry) p->next = new ListNode(1);
p = head->next;
return p;
}
};