首页 > 代码库 > LeetCode OJ - Add Two Numbers

LeetCode OJ - 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         if (l1 == NULL) return l2;13         if (l2 == NULL) return l1;14         15         ListNode* head = new ListNode((l1->val + l2->val) % 10);16         int carry = (l1->val + l2->val) / 10;17         ListNode* p1 = l1->next, *p2 = l2->next;18         19         ListNode* cur = head;20         while (p1 != NULL && p2 != NULL) {21             int tmp = p1->val + p2->val + carry;22             cur->next = new ListNode(tmp % 10);23             carry = tmp / 10;24             p1 = p1->next;25             p2 = p2->next;26             cur = cur->next;27         }28         while (p1 != NULL) {29             int tmp = p1->val + 0 + carry;30             cur->next = new ListNode(tmp % 10);31             carry = tmp / 10;32             p1 = p1->next;33             cur = cur->next;34         }35         while (p2 != NULL) {36             int tmp = p2->val + 0 + carry;37             cur->next = new ListNode(tmp % 10);38             carry = tmp / 10;39             p2 = p2->next;40             cur = cur->next;41         }42         if (carry) {43             cur->next = new ListNode(carry);44         }45         return head;46     }47 };