1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { val = x; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { int t = 0; ListNode left = l1; ListNode right = l2; boolean flat = true; ListNode result = null; ListNode header = null; while(flat){ flat = false; if (left!=null){ t = t+left.val; left = left.next; flat = true; } if (right!=null){ t = t+right.val; right = right.next; flat = true; } if (flat || t!=0){ int x = t % 10; t = t/10; if (result==null){ result = new ListNode(x); header = result; }else{ ListNode next = new ListNode(x); result.next = next; result = next; } } } return header; } }
|
近期评论