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
Output: 7 -> 0 -> 8
It is always fun to manipulate linklist.
Iterates, add one by one.
All methods can be optimized with early stop condition (when one linklist reaches null and 0 == carry).
1. Iterates till end of one linklist, use the second loop to do the rest job.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode preHead = new ListNode(-1); ListNode x = preHead; while(null != l1 && null != l2){ carry += l1.val+l2.val; preHead.next = new ListNode(carry % 10); carry /= 10; preHead = preHead.next; l1 = l1.next; l2 = l2.next; } ListNode head = null == l1 ? l2 : l1; while( null != head){ carry += head.val; preHead.next = new ListNode(carry % 10); carry /= 10; preHead = preHead.next; head = head.next; } if(0 != carry) preHead.next = new ListNode(carry); return x.next; } }2. Use one loop, add 0 if link list reaches end.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { if(null == l1) return l2; if(null == l2) return l1; int carry = 0; ListNode pre = new ListNode(0); ListNode res = pre; while(0 != carry || l1 != null || l2 != null){ carry += (null == l1 ? 0 : l1.val) + (null == l2 ? 0 : l2.val); pre.next = new ListNode(carry % 10); carry /= 10; pre = pre.next; l1 = null == l1 ? l1 : l1.next; l2 = null == l2 ? l2 : l2.next; } return res.next; } }
3. Variants, like implement += operation, add value based on l1.
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int carry = 0; ListNode res = l1; ListNode pl1 = new ListNode(0); pl1.next = l1; while(0 != carry || null != pl1.next || null != l2){ if(null == pl1.next) pl1.next = new ListNode(0); carry += pl1.next.val + (null == l2? 0: l2.val); pl1.next.val = carry % 10; carry /= 10; pl1 = pl1.next; l2 = (null == l2? null : l2.next); } return l1; } }
No comments:
Post a Comment