/* * @lc app=leetcode id=2 lang=java * * [2] Add Two Numbers */ // @lc code=start /** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { boolean propagated = false; ListNode r = null, cur = null; while(l1!=null ||l2!=null) { int v1 = l1!=null?l1.val:0; int v2 = l2!=null?l2.val:0; int v = v1 + v2 + (propagated?1:0); propagated = v/10!=0; v = v %10; // add node to result ListNode t = new ListNode(v); t.next = null; if(r == null) { r = t; cur = t; } else { cur.next = t; cur = cur.next; } if(l1!=null) { l1 = l1.next; } if(l2!=null) { l2 = l2.next; } } if(propagated) { ListNode t = new ListNode(1); t.next = null; cur.next = t; cur = cur.next; } return r; } } // @lc code=end