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
需要注意的是进位和指针操作!
点击(此处)折叠或打开
- /**
- * 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 *result = l1;
- ListNode *p1 = l1;
- ListNode *p2 = l2;
- ListNode *pre = l1;
- int s = 0;
- while (p1 && p2) {
- pre = p1;
- int temp = s;
- s = (p1->val + p2->val + s) / 10;
- p1->val = (p1->val + p2->val + temp) % 10;
- p1 = p1->next;
- p2 = p2->next;
- }
- if (p2) {
- pre->next = p2;
- p1 = p2;
- }
- while (p1) {
- pre = p1;
- if (s != 0) {
- int temp = s;
- s = (p1->val + s) / 10;
- p1->val = (p1->val + temp) % 10;
- p1 = p1->next;
- } else {
- break;
- }
- }
- if (s) {
- pre->next = new ListNode(s);
- }
- return result;
- }
- };