leetcode_question_2 Add Two Numbers

来源:互联网 发布:马里兰艺术学院 知乎 编辑:程序博客网 时间:2024/06/13 10:59

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) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        if(l1 == NULL) return l2;if(l2 == NULL) return l1;ListNode* p1 = l1;ListNode* p2 = l2;ListNode* head = NULL;ListNode* p;bool carry = false;while(p1 != NULL && p2 != NULL){int sum = p1->val + p2->val;if(carry){ ++sum; carry=false; }if(sum > 9){ carry = true; sum -= 10; }ListNode* tmp = new ListNode(sum);if(head == NULL){head = tmp;p = head;}else{p->next = tmp;p = tmp;}p1 = p1->next;p2 = p2->next;}if(carry){if(p1 != NULL){while(p1){int sum = p1->val;if(carry){ ++sum; carry=false; }if(sum > 9){ carry = true; sum -= 10; }ListNode* tmp = new ListNode(sum);p->next = tmp;p = p->next;p1= p1->next;}if(carry){ListNode* tmp = new ListNode(1);p->next = tmp;}}else if(p2 != NULL){while(p2){int sum = p2->val;if(carry){ ++sum; carry=false; }if(sum > 9){ carry = true; sum -= 10; }ListNode* tmp = new ListNode(sum);p->next = tmp;p = p->next;p2= p2->next;}if(carry){ListNode* tmp = new ListNode(1);p->next = tmp;}}else{ListNode* tmp = new ListNode(1);p->next = tmp;}}else{if(p1)p->next = p1;elsep->next = p2;}return head;    }};


原创粉丝点击