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 if(!l1) 13 return l2; 14 else if(!l2) 15 return l1; 16 17 ListNode *dummy = new ListNode(0); 18 ListNode *head = nullptr, *start = dummy; 19 int carry = 0; 20 while(l1 || l2) 21 { 22 if(l1 && l2) 23 { 24 int sum = l1->val + l2->val + carry; 25 l1->val = sum % 10; 26 carry = sum / 10; 27 start->next = l1; 28 l1 = l1->next; 29 l2 = l2->next; 30 } 31 else if(l1) 32 { 33 int sum = l1->val + carry; 34 l1->val = sum % 10; 35 carry = sum / 10; 36 start->next = l1; 37 l1 = l1->next; 38 } 39 else 40 { 41 int sum = l2->val + carry; 42 l2->val = sum % 10; 43 carry = sum / 10; 44 start->next = l2; 45 l2 = l2->next; 46 } 47 48 start = start->next; 49 } 50 51 if(carry) 52 { 53 ListNode *node = new ListNode(1); 54 start->next = node; 55 } 56 57 head = dummy->next; 58 delete dummy; 59 dummy = nullptr; 60 61 return head; 62 } 63 };