俩数相加

给定两个非空链表来代表两个非负整数。数字最高位位于链表开始位置。它们的每个节点只存储单个数字。将这两数相加会返回一个新的链表。

你可以假设除了数字 0 之外,这两个数字都不会以零开头。

进阶:

如果输入链表不能修改该如何处理?换句话说,你不能对列表中的节点进行翻转。

示例:

输入: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)
输出: 7 -> 8 -> 0 -> 7

解法1:

  

public static class ListNode {
    private int val;
    private ListNode next;

    public ListNode(int val) {
      this.val = val;
    }
  }

  public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    /*翻转链表*/
    ListNode r1 = reverse(l1);
    /*翻转链表*/
    ListNode r2 = reverse(l2);
    /*定义新链表的哑节点*/
    ListNode dumb = new ListNode(0);
    /*定义一个引用指向哑节点*/
    ListNode r = dumb;
    /*加数*/
    int add = 0;
    /*遍历2个链表*/
    while (r1 != null || r2 != null) {
      int val = add;
      add = 0;
      if (r1 != null) {
        val = val + r1.val;
        r1 = r1.next;
      }
      if (r2 != null) {
        val = val + r2.val;
        r2 = r2.next;
      }
      if (val >= 10) {
        val = val - 10;
        add = 1;
      }
      dumb.next = new ListNode(val);
      dumb = dumb.next;
    }
    if (add > 0) {
      dumb.next = new ListNode(add);
    }
    /*翻转新链表*/
    return reverse(r.next);
  }

  public static ListNode reverse(ListNode head) {
    ListNode pre = null;
    while (head != null) {
      ListNode tmp = head.next;
      head.next = pre;
      pre = head;
      head = tmp;
    }
    return pre;
  }
View Code

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers-ii

猜你喜欢

转载自www.cnblogs.com/wuyouwei/p/11823020.html