【Leetcode】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 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
12         ListNode *p1 = l1, *p2 = l2, dummy(-1), *tail = &dummy;
13         int sum = 0, carry = 0;
14         while (p1 != nullptr || p2 != nullptr) {
15             int v1 = p1 == nullptr ? 0 : p1->val;
16             int v2 = p2 == nullptr ? 0 : p2->val;
17             p1 = p1 == nullptr ? nullptr : p1->next;
18             p2 = p2 == nullptr ? nullptr : p2->next;
19 
20             sum = v1 + v2 + carry;
21             tail->next = new ListNode(sum % 10);
22             tail = tail->next;
23             carry = sum / 10;
24         }
25         if (carry > 0) {
26             tail->next = new ListNode(carry);
27             tail = tail->next;
28         }
29         return dummy.next;
30     }
31 };
View Code

Add binary类似,思想与方法完全一样,只是用链表实现,在链表前加哑元素可以使尾插入的代码简化。

posted @ 2014-03-20 13:16  小菜刷题史  阅读(133)  评论(0编辑  收藏  举报