1. 问题描述
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
Similar Problems: (M) Multiply Strings (E) Add Binary
2. 解答思路
3. 代码
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 #include <iostream> 10 using namespace std; 11 struct ListNode { 12 int val; 13 ListNode *next; 14 ListNode(int x) : val(x), next(NULL) {} 15 }; 16 class Solution { 17 public: 18 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 19 if (NULL == l1) 20 { 21 return l2; 22 } 23 if (NULL == l2) 24 { 25 return l1; 26 } 27 return addTwoNum(l1, l2); 28 } 29 public: 30 void PrintList(ListNode* l1) 31 { 32 if (NULL == l1) 33 { 34 return; 35 } 36 ListNode *pt = l1; 37 while (NULL != pt) 38 { 39 std::cout<< pt->val << " "; 40 pt = pt->next; 41 } 42 43 } 44 private: 45 ListNode* addTwoNum(ListNode* ptLar, ListNode* ptSma) 46 { 47 ListNode *pLar = ptLar; 48 ListNode *pSma = ptSma; 49 int t = 0; 50 while (NULL != pSma && NULL != pLar) 51 { 52 int sum = pLar->val + pSma->val + t; 53 pLar->val = sum%10; 54 pSma->val = pLar->val; 55 t = sum/10; 56 if ((NULL != pSma->next && NULL != pLar->next)) 57 { 58 pSma = pSma->next; 59 pLar = pLar->next; 60 } 61 else 62 { 63 break; 64 } 65 66 } 67 68 if (0 == t) 69 { 70 if (NULL == pSma->next) 71 { 72 return ptLar; 73 } 74 else 75 { 76 return ptSma; 77 } 78 } 79 80 if (NULL == pSma->next && NULL == pLar->next) 81 { 82 ListNode *pNew = new ListNode(1); 83 pLar->next = pNew; 84 return ptLar; 85 } 86 87 if ( NULL != pLar->next) 88 { 89 addone(pLar); 90 return ptLar; 91 } 92 else 93 { 94 addone(pSma); 95 return ptSma; 96 } 97 98 } 99 void addone(ListNode *pLar, int t = 1) 100 { 101 pLar = pLar->next; 102 while (NULL != pLar) 103 { 104 int sum = pLar->val + t; 105 pLar->val = sum%10; 106 t = sum/10; 107 if (0 == t) 108 { 109 break; 110 } 111 else 112 { 113 if (NULL == pLar->next) 114 { 115 ListNode *pNew = new ListNode(1); 116 pLar->next = pNew; 117 break; 118 } 119 else 120 { 121 pLar = pLar->next; 122 } 123 } 124 } 125 } 126 };