Add Two Numbers

描述

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

分析

Add Binary 很类似

代码

  1. // Add Two Numbers
  2. // 跟Add Binary 很类似
  3. // 时间复杂度O(m+n),空间复杂度O(1)
  4. public class Solution {
  5. public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
  6. ListNode dummy = new ListNode(-1); // 头节点
  7. int carry = 0;
  8. ListNode prev = dummy;
  9. for (ListNode pa = l1, pb = l2;
  10. pa != null || pb != null;
  11. pa = pa == null ? null : pa.next,
  12. pb = pb == null ? null : pb.next,
  13. prev = prev.next) {
  14. final int ai = pa == null ? 0 : pa.val;
  15. final int bi = pb == null ? 0 : pb.val;
  16. final int value = (ai + bi + carry) % 10;
  17. carry = (ai + bi + carry) / 10;
  18. prev.next = new ListNode(value); // 尾插法
  19. }
  20. if (carry > 0)
  21. prev.next = new ListNode(carry);
  22. return dummy.next;
  23. }
  24. };

相关题目

原文: https://soulmachine.gitbooks.io/algorithm-essentials/content/java/linear-list/linked-list/add-two-numbers.html