[LeetCode] Add Two Numbers(stored in List)
首先,演示一个错误的reverList
1 class Solution { 2 public: 3 ListNode* reverse(ListNode* root) 4 { 5 if(NULL == root) 6 return NULL; 7 ListNode* pCur = root; 8 ListNode* pNext = root->next; 9 10 while(pNext) 11 { 12 pNext = pNext->next; 13 pCur->next->next = pCur; 14 pCur = pCur->next; 15 } 16 root->next = NULL; 17 return pCur; 18 } 19 20 };
(2)--------->(3)-------->(4)----------->(5)--------->NULL
首先pCur指向2,pNext指向3;
pNext=pNext->next; pNext指向4,
pCur->next->next = pCur,然后3--->4 的指针断了, 从此pCur就自己转圈了。。。
正确的reverseList
ListNode * reverseList(ListNode* head) { if(head == NULL) return NULL; ListNode *pre = NULL; ListNode *cur = head; ListNode *next = NULL; while(cur) { next = cur->next; cur->next = pre; pre = cur; cur = next; } return pre; }
这个题目也不难,注意dummy节点的使用,另外,记得最后carrybit的处理
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { if(l1 == NULL) return l2; if(l2 == NULL) return l1; ListNode* p1 = l1; ListNode* p2 = l2; ListNode dummy(-1); ListNode* pNew = &dummy; int carry = 0; int sum = 0; while(p1 && p2) { sum = (p1->val + p2->val + carry)%10; carry= (p1->val + p2->val + carry)/10; pNew->next = new ListNode(sum); pNew = pNew->next; p1 = p1->next; p2 = p2->next; } while(p1) { sum = (p1->val + carry)%10; carry= (p1->val + carry)/10; pNew->next = new ListNode(sum); pNew = pNew->next; p1 = p1->next; } while(p2) { sum = (p2->val + carry)%10; carry= (p2->val + carry)/10; pNew->next = new ListNode(sum); pNew = pNew->next; p2 = p2->next; } if(carry) { pNew->next = new ListNode(carry); pNew = pNew->next; } return dummy.next; } };