- 下面是我的算法
一开始采用的是while(ln2 != null && ln1 != null) 结果答案就是解不出
然后采用下面更加啰嗦的 就好了~
/** * 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) { ListNode head = new ListNode(0); ListNode ln = head; ListNode ln1 = l1; ListNode ln2 = l2; int temp = 0; while (ln1 != null || ln2 != null) { if (ln1 == null) { ln.next = new ListNode((ln2.val + temp) % 10); temp = (ln2.val + temp) / 10; ln = ln.next; } else if (ln2 == null) { ln.next = new ListNode((ln1.val + temp) % 10); temp = (ln1.val + temp) / 10; ln = ln.next; } else { ln.next = new ListNode((ln1.val + ln2.val + temp) % 10); temp = (ln1.val + ln2.val + temp) / 10; ln = ln.next; } } if (temp != 0) ln.next = new ListNode(1); return head.next; } }
简化版:
public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode dummyHead = new ListNode(0); ListNode p = l1, q = l2, curr = dummyHead; int carry = 0; while (p != null || q != null) { int x = (p != null) ? p.val : 0; int y = (q != null) ? q.val : 0; int sum = carry + x + y; carry = sum / 10; curr.next = new ListNode(sum % 10); curr = curr.next; if (p != null) p = p.next; if (q != null) q = q.next; } if (carry > 0) { curr.next = new ListNode(carry); } return dummyHead.next; }
public class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode ln1 = l1, ln2 = l2, head = null, node = null; int carry = 0, remainder = 0, sum = 0; head = node = new ListNode(0); while(ln1 != null || ln2 != null || carry != 0) { sum = (ln1 != null ? ln1.val : 0) + (ln2 != null ? ln2.val : 0) + carry; carry = sum / 10; remainder = sum % 10; node = node.next = new ListNode(remainder); ln1 = (ln1 != null ? ln1.next : null); ln2 = (ln2 != null ? ln2.next : null); } return head.next; } }