标签:res tno ext tips ref obj change add caller
Tips: Tried to use a private method to simplize the code. But found that object is passed by reference. So even if you have ListNode as l, and l = l.next, it is reference change. It will not impac the object in caller function.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 if (l1 == null) { 12 return l2; 13 } 14 15 if (l2 == null) { 16 return l1; 17 } 18 ListNode result = new ListNode(0); 19 ListNode tail = result; 20 int c = 0; 21 while (l1 != null || l2 != null) { 22 int n1 = 0; 23 int n2 = 0; 24 if (l1 != null) { 25 n1 = l1.val; 26 l1 = l1.next; 27 } 28 29 if (l2 != null) { 30 n2 = l2.val; 31 l2 = l2.next; 32 } 33 tail.next = new ListNode((n1 + n2 + c)%10); 34 tail = tail.next; 35 c = (n1 + n2 + c) / 10; 36 } 37 38 if (c > 0) { 39 tail.next = new ListNode(c); 40 } 41 42 return result.next; 43 } 44 }
标签:res tno ext tips ref obj change add caller
原文地址:http://www.cnblogs.com/shuashuashua/p/7233599.html