标签:
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
Tags:Linked List, Math
分析:逐位相加,考虑进位。
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 || !l2) { 13 return NULL; 14 } 15 int carry = 0; //进位 16 ListNode * result = new ListNode(0); 17 ListNode * first = result; //追踪结果链表的当前节点 18 ListNode * pre = NULL; //追踪结果链表的前一个节点 19 //当l1和l2均没有超过链表末尾节点时 20 while (l1 && l2) { 21 first->val = (carry + l1->val + l2->val) % 10; 22 carry = (carry + l1->val + l2->val) / 10; 23 if (pre == NULL) 24 pre = first; 25 else { 26 pre->next = first; 27 pre = first; 28 } 29 first = new ListNode(0); 30 l1 = l1->next; 31 l2 = l2->next; 32 } 33 //当l1和l2都超过链表末尾节点时 34 if (!l1 && !l2) { 35 if (carry == 1) { 36 first->val = carry; 37 pre->next = first; 38 } 39 return result; 40 } 41 //当l1超过末尾而l2尚未超过时 42 if (!l1 && l2) { 43 while (l2) { 44 first->val = (carry + l2->val) % 10; 45 carry = (carry + l2->val) / 10; 46 if (pre == NULL) 47 pre = first; 48 else { 49 pre->next = first; 50 pre = first; 51 } 52 first = new ListNode(0); 53 l2 = l2->next; 54 } 55 if (carry == 1) { 56 first->val = 1; 57 pre->next = first; 58 } 59 return result; 60 } 61 //当l2超过末尾而l1尚未超过时 62 if (!l2 && l1) { 63 while (l1) { 64 first->val = (carry + l1->val) % 10; 65 carry = (carry + l1->val) / 10; 66 if (pre == NULL) 67 pre = first; 68 else { 69 pre->next = first; 70 pre = first; 71 } 72 first = new ListNode(0); 73 l1 = l1->next; 74 } 75 if (carry == 1) { 76 first->val = 1; 77 pre->next = first; 78 } 79 return result; 80 } 81 82 } 83 };
标签:
原文地址:http://www.cnblogs.com/chen0958/p/4355982.html