/*** * You are given two non-empty linked lists representing two non-negative integers. * 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. * * You may assume the two numbers do not contain any leading zero, except the number 0 itself. * * Example: * * Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) * Output: 7 -> 0 -> 8 * Explanation: 342 + 465 = 807. * */
/** * Definition for singly-linked list. */ public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } }
public class N002_AddTwoNumbers { public static ListNode add(ListNode l1, ListNode l2) { /*** * 多餘的步驟! if (l1 == null) { return l2; } if (l2 == null) { return l1; } ***/ ListNode result = new ListNode(-1); //關鍵步驟,要多一個頭節點用來返回結果 ListNode l3 = result; int value = 0; while (l1 != null || l2 != null) { if (l1 != null) { value = value + l1.val; l1 = l1.next; } if (l2 != null) { value = value + l2.val; l2 = l2.next; } l3.next = new ListNode(value % 10); l3 = l3.next; value = value / 10; } /*** * 最後一步的進位檢測,很容易漏!!! */ if(value==1) l3.next=new ListNode(1); return result.next; } public static void main(String args[]) { ListNode l1tmp2 = new ListNode(8); ListNode l1tmp1 = new ListNode(5); l1tmp1.next = l1tmp2; ListNode l1 = new ListNode(3); l1.next = l1tmp1; printListNode(l1); ListNode l2tmp2 = new ListNode(2); ListNode l2tmp1 = new ListNode(8); l2tmp1.next = l2tmp2; ListNode l2 = new ListNode(7); l2.next = l2tmp1; printListNode(l2); ListNode result = add(l1, l2); printListNode(result); } private static void printListNode(ListNode ln) { String out = ""; ListNode tmp = ln; out = tmp.val + out; while (tmp.next != null) { tmp = tmp.next; out = tmp.val + out; } System.out.println(out); } }