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 -> 8Explanation: 342 + 465 = 807.
thinking
加法运算规则,指针的操作
solution
public class AddTwoNumbers { public class ListNode { int val; ListNode next; ListNode(int x) { val = x; } [@Override](https://my.oschina.net/u/1162528) public String toString() { StringBuilder sb = new StringBuilder(); sb.append(val); ListNode pointer = next; while(pointer != null) { sb.append("->"); sb.append(pointer.val); pointer = pointer.next; } return sb.toString(); } /* * 借助toString 判断链表相等 * [@see](https://my.oschina.net/weimingwei) java.lang.Object#toString() */ [@Override](https://my.oschina.net/u/1162528) public boolean equals(Object obj) { if(!(obj instanceof ListNode)) return false; return this.toString().equals(((ListNode)obj).toString()); } } //假设l1,l2都是合法参数,返回新的链表 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { //进位 int carry = 0; ListNode head = null, tail = null; while(l1 != null || l2 != null) { int a = l1 != null ? l1.val : 0 ; int b = l2 != null ? l2.val : 0; int sum = a + b + carry; carry = sum / 10; ListNode tmp = new ListNode(sum % 10); if(head == null && tail == null) { head = tail = tmp; }else { tail.next = tmp; tail = tail.next; } if(l1 != null) { l1 = l1.next; } if(l2 != null) { l2 = l2.next; } } if(carry != 0) { tail.next = new ListNode(carry); tail = tail.next; } return head; } //辅助,非负数逆序队列,用队列实现 public ListNode transform(int from) { //个位 int digit = from % 10; ListNode tail = new ListNode(digit); ListNode head = tail; from = (from - digit) / 10; while(from > 0) { digit = from % 10; tail.next = new ListNode(digit); tail = tail.next; from = (from - digit) / 10; } return head; } @//Test public void testTransform() { assertEquals("1", transform(1).toString()); assertEquals("9->8->7->6->9->8->7->6", transform(67896789).toString()); assertEquals("3->2->1", transform(123).toString()); assertEquals(transform(123).toString(), transform(123).toString()); } @//Test public void testAddTwoNumbers() { assertEquals("2->2->2", addTwoNumbers(transform(111), transform(111)).toString()); assertEquals("7->0->8", addTwoNumbers(transform(342), transform(465)).toString()); assertEquals("0->0->0->1", addTwoNumbers(transform(990), transform(10)).toString()); }}
reference