Bootstrap

leetcode2.两数相加(java)

思路

这道题最开始遇到的问题是题目理解错了。
使用链表逆序存数,也就是头节点就是个位,开始以为要遍历到尾节点开始算(可能正常人都不会这么想)

补零法
如果节点为空,则该节点值为0

int x = l1 == null ? 0 : l1.val;
int y = l2 == null ? 0 : l2.val;

进位

用carry表示进位

int result = x + y + carry;
carry = result / 10;

注意,最后一个进位不要忘记,如果有的话。

if(carry == 1){
   cur.next = new ListNode(1);
}

指针的移动
如何保留住头节点的位置
使用两个指针,pre,cur。pre指向头节点,后面只移动cur

代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        int carry = 0;
        while(l1 != null || l2 != null){
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int result = x + y + carry;
            carry = result / 10;
            result = result % 10;
            cur.next = new ListNode(result);
            cur = cur.next;
            if(l1 != null){
                l1 = l1.next;
            } 
            if(l2 != null){
                l2 = l2.next;
            }
        }
        if(carry == 1){
            cur.next = new ListNode(1);
        }
        return pre.next;
    }
}
;