Add Two Numbers

来源:互联网 发布:法院网络司法拍卖 编辑:程序博客网 时间:2024/05/17 04:55

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){        int carry = 0;ListNode* head = 0;ListNode* cur = 0;while ( l1 != 0 || l2 != 0){int val = 0;if (l1 != 0)val += l1->val;if (l2 != 0)val += l2->val;if (carry != 0)val += carry;carry = (val / 10 > 0 ? val / 10 : 0);ListNode* tmp = new ListNode(val % 10);if (head == 0){head = tmp;cur = tmp;}else{cur->next = tmp;cur = cur->next;}if (l1 != 0)l1 = l1->next;if (l2 != 0)l2 = l2->next;}if (carry != 0){ListNode* tmp = new ListNode(carry);cur->next = tmp;}return head;    }};


0 0