0369. Plus One Linked List

369. Plus One Linked List #

题目 #

给定一个用 链表 表示的非负整数,然后将这个整数加一。

最高位有效数字位于链表的首尾 head

思路 #

代码 #

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 int helper(ListNode head, int carry) {
        if (head.next == null) {
            int result = (head.val + carry) / 10;
            head.val = (head.val + carry) % 10;
            return result;
        } else {
            int newCarry = helper(head.next, carry);
            int result = (head.val + newCarry) / 10;
            head.val = (head.val + newCarry) % 10;
            return result;
        }
    }
    public ListNode plusOne(ListNode head) {
        int carry = helper(head, 1);
        if (carry == 0) return head;
        else return new ListNode(carry ,head);
    }
}