LeetCode #2 Add Two Numbers Cpp Solution
2016-04-04 11:54
537 查看
LeetCode #2 Problem
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
一个高精度加法的链表实现。
自己的代码太丑,贴个别人的吧。
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
一个高精度加法的链表实现。
自己的代码太丑,贴个别人的吧。
code from http://blog.csdn.net/feliciafay/article/details/16978487 class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if((l1==NULL)&&(l2==NULL)) { return NULL; } int sum = 0; ListNode *root = NULL; ListNode *tail = NULL; while(l1 != NULL || l2 != NULL) { if (l1 != NULL) { sum += l1->val; l1 = l1->next; } if (l2 != NULL) { sum += l2->val; l2 = l2->next; } ListNode *p = new ListNode(sum % 10); if (root == NULL) { root = p; tail = p; } else { tail->next = p; tail = p; } sum/=10; } if (sum != 0) { ListNode *p = new ListNode(sum % 10); if (root == NULL) { root = p; tail = p; } else { tail->next = p; tail = p; } } return root; } };