Add Two Numbers(not optimized)

xiaoxiao2021-02-28  31

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.

/** * 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; ListNode * q = l2; ListNode * ret = l1; ListNode * pre = p; int c = 0;//jin wei while(p != nullptr && q != nullptr){ int val = p->val+q->val + c; p->val = val % 10; c = val / 10; pre = p; p = p->next; q = q->next; } while(p != nullptr){ int val = p->val + c; p->val = val % 10; c = val / 10; pre = p; p = p->next; } while(q != nullptr){ int val = q->val + c; pre -> next = new ListNode(val % 10); pre = pre -> next; c = val / 10; q = q->next; } if(c != 0){ pre -> next = new ListNode(c); } return ret; } };

转载请注明原文地址: https://www.6miu.com/read-2624127.html

最新回复(0)