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
Solution1:不用分配多余的空间,但是会改变原先lists中的值。
/** * 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) { if(l1==null&&l2==null) return null; if(l1==null) return l2; if(l2==null) return l1; ListNode ptr1 = l1, ptr2 = l2; int c = 0; ListNode prev=l1;//reserve the previous value in the generated list while(ptr1!=null && ptr2!=null){ ptr1.val = ptr1.val+ptr2.val+c; c = ptr1.val/10; ptr1.val = ptr1.val%10; prev = ptr1; ptr1=ptr1.next; ptr2=ptr2.next; } if(ptr2!=null) { //ptr1==null prev.next = ptr2; ptr1 = ptr2; ptr2=null; //must do this for maintaining end condition } while(c!=0&&ptr1!=null){ ptr1.val =ptr1.val+c; c = ptr1.val/10; ptr1.val = ptr1.val%10; prev = ptr1; ptr1 = ptr1.next; } if(c!=0&&ptr1==null&&ptr2==null) { ListNode newNode =new ListNode(1); prev.next = newNode; ptr1 = newNode; } return l1; } }
Solution 2: 不会改变原lists中的值,但需建立一个新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) { if(l1==null&&l2==null) return null; if(l1==null) return l2; if(l2==null) return l1; ListNode head = new ListNode(0); int c = 0; ListNode prev=head;//reserve the previous value in the generated list while(l1!=null || l2!=null){ ListNode cur = new ListNode(0); if(l1!=null){ cur.val += l1.val; l1=l1.next; } if(l2!=null){ cur.val += l2.val; l2=l2.next; } cur.val += c; c = cur.val/10; cur.val = cur.val%10; prev.next = cur; prev = cur; } if(c!=0) { ListNode newNode =new ListNode(1); prev.next = newNode; } return head.next; } }
时间: 2024-09-29 18:14:33