标签:
/**
* ID: 2
* Name: Add Two Numbers
* Data Structure: Linked List
* Time Complexity:
* Space Complexity:
* Tag: LinkList
* Difficult: Medium
* Problem:
* 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
思路一: 本题主要注意谁先遍历结束,而且注意进位的问题,carry,就是当没有新的node,但还有carry的时候,就要新加一个node进去。
在两个链表没有都没结束,互加,进位,然后把L2合并到L1 里面去,然后在让L1 走完,完成进位的所有操作.
思路二: 建立一个全新的List,然后每次对L1,L2,carry的值分别加进去,最后返回一个新的List.
1 class Solution { 2 public: 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4 if(l1 == NULL) 5 return l2; 6 if(l2 == NULL) 7 return l1; 8 9 ListNode *fakeNode1 = new ListNode(0); 10 ListNode *fakeNode2 = new ListNode(0); 11 fakeNode1 -> next = l1; 12 fakeNode2 -> next = l2; 13 ListNode *p1 = fakeNode1; 14 ListNode *p2 = fakeNode2; 15 int carry = 0; 16 int sum = 0; 17 18 while(p1->next && p2->next) 19 { 20 p1 = p1->next; 21 p2 = p2->next; 22 sum = carry + p1->val + p2->val; 23 carry = sum/10; 24 p1->val = sum%10; 25 26 } 27 28 if(p1->next==NULL && p2->next!=NULL) 29 { 30 p1->next = p2->next; 31 } 32 delete p2; 33 delete fakeNode2; 34 while(p1->next) 35 { 36 p1 = p1->next; 37 sum = carry + p1->val ; 38 carry = sum/10; 39 p1->val = sum%10; 40 } 41 if(carry!=0) 42 { 43 ListNode *last = new ListNode(carry); 44 p1->next = last; 45 } 46 return fakeNode1->next; 47 } 48 };
思路二:
1 class Solution { 2 public: 3 ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { 4 ListNode *dummy = new ListNode(0), *p = dummy; 5 int carry = 0; 6 while(l1 || l2 || carry) { 7 if(l1) { 8 carry+=l1->val; 9 l1 = l1->next; 10 } 11 if(l2) { 12 carry+=l2->val; 13 l2 = l2->next; 14 } 15 p->next = new ListNode(carry%10); // every time create a new node. 16 carry /= 10; 17 p = p->next; 18 } 19 return dummy->next; 20 } 21 };
标签:
原文地址:http://www.cnblogs.com/zhuguanyu33/p/4421193.html