Skip to content

Latest commit

 

History

History
33 lines (28 loc) · 1.1 KB

2. Add Two Numbers.md

File metadata and controls

33 lines (28 loc) · 1.1 KB

#2. 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

思路:两个链表相加,每个节点的数字都为个位数,需要进位。那么相加循环的条件有三个:l1链表一不为空 l2链表二不为空 decimal进位数不为零。

Java Solution(neat)

public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
      ListNode pre = new ListNode(0);
      ListNode head = pre;
      int decimal = 0;
       while (l1 != null || l2 != null || decimal != 0) {
          ListNode cur = new ListNode(0);
          int sum = ((l2 == null) ? 0 : l2.val) + ((l1 == null) ? 0 : l1.val) + decimal;
          cur.val = sum % 10;
          decimal = sum / 10;
          pre.next = cur; 
          pre = cur;
          l1 = (l1 == null) ? l1 : l1.next;
          l2 = (l2 == null) ? l2 : l2.next;
       }
    return head.next;
}
}