LeetCode-Add Two Numbers
Add Two Numbers Nov 1 '11 5998 / 20033
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
可能出现一条链表比另一条链表长的情况,需要注意进位
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 // Start typing your C/C++ solution below 13 // DO NOT write int main() function 14 15 ListNode* head=new ListNode(0); 16 ListNode* ret=head; 17 bool carry=false; 18 while(l1!=NULL&&l2!=NULL){ 19 int sum=l1->val+l2->val; 20 if(carry){sum++;carry=false;} 21 if(sum>9) 22 { 23 carry=true; 24 sum-=10; 25 } 26 ret->next=new ListNode(sum); 27 ret=ret->next; 28 l1=l1->next; 29 l2=l2->next; 30 } 31 while(l1!=NULL){ 32 int sum=l1->val; 33 if(carry){sum++;carry=false;} 34 if(sum>9) 35 { 36 carry=true; 37 sum-=10; 38 } 39 ret->next=new ListNode(sum); 40 ret=ret->next; 41 l1=l1->next; 42 } 43 while(l2!=NULL){ 44 int sum=l2->val; 45 if(carry){sum++;carry=false;} 46 if(sum>9) 47 { 48 carry=true; 49 sum-=10; 50 } 51 ret->next=new ListNode(sum); 52 ret=ret->next; 53 l2=l2->next; 54 } 55 56 if(carry){ 57 ret->next=new ListNode(1); 58 } 59 return head->next; 60 } 61 };
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { // Note: The Solution object is instantiated only once and is reused by each test case. if(l1==null&&l2==null)return null; if(l1==null)return l2; if(l2==null)return l1; boolean carry=false; ListNode ret=new ListNode(-1); ListNode current=ret; while(l1!=null&&l2!=null){ int val=l1.val+l2.val; if(carry){ val++; carry=false; } if(val>=10){ carry=true; val-=10; } current.next=new ListNode(val); current=current.next; l1=l1.next; l2=l2.next; } while(l1!=null){ int val=l1.val; if(carry){ val++; carry=false; } if(val>=10){ carry=true; val-=10; } current.next=new ListNode(val); current=current.next; l1=l1.next; } while(l2!=null){ int val=l2.val; if(carry){ val++; carry=false; } if(val>=10){ carry=true; val-=10; } current.next=new ListNode(val); current=current.next; l2=l2.next; } if(carry){ current.next=new ListNode(1); } return ret.next; } }