标签:
1 struct ListNode { 2 int val; 3 ListNode *next; 4 ListNode(int x) : val(x), next(NULL) {} 5 }; 6 7 class Solution { 8 public: 9 ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { 10 11 if (l1 == NULL) 12 return l2; 13 if (l2 == NULL) 14 return l1; 15 16 unsigned long int v1 = -1, v2 = -1, v3 = 0; 17 18 ListNode *p1 = l1, *p2 = l2, *l3 = NULL, *p3 = l3; 19 ListNode *pt = NULL; 20 int count = 0; 21 while (p1){ 22 if ( count==0 ) 23 v1 = p1->val; 24 else{ 25 int temp=1; 26 for (int i = 1; i <= count; i++) 27 temp = 10 * temp; 28 29 v1 = temp* (p1->val) + v1; 30 } 31 32 count++; 33 p1 = p1->next; 34 } 35 36 count = 0; 37 while (p2){ 38 if (count == 0) 39 v2 = p2->val; 40 else{ 41 int temp = 1; 42 for (int i = 1; i <= count; i++) 43 temp = 10 * temp; 44 45 v2 = temp* (p2->val) + v2; 46 } 47 48 count++; 49 p2 = p2->next; 50 } 51 52 v3 = v1 + v2; 53 54 while (v3 / 10 != 0){ 55 pt = new ListNode(v3 % 10); 56 if (l3 == NULL){ 57 pt->next = NULL; 58 l3 = pt; 59 } 60 else{ 61 pt->next = p3->next; 62 p3->next = pt; 63 p3 = pt; 64 } 65 v3 = v3 / 10; 66 p3 = pt; 67 } 68 if (v3 != 0){ 69 pt = new ListNode(v3); 70 pt->next = p3->next; 71 p3->next = pt; 72 p3 = pt; 73 } 74 75 p3->next = NULL; 76 77 return l3; 78 } 79 };
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
在 VS 下能通过各种测试用例,但leetcode上就是不行 ~~ 留着查原因
标签:
原文地址:http://www.cnblogs.com/sprint1989/p/4756972.html