369. Plus One Linked List

Given a non-negative number represented as a singly linked list of digits, plus one to the number.

The digits are stored such that the most significant digit is at the head of the list.

Example: Input: 1->2->3

Output: 1->2->4

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode plusOne(ListNode head) {
        int c = po(head);
        if(c != 0){
            ListNode newHead = new ListNode(c);
            newHead.next = head;
            head = newHead;
        }

        return head;
    }

    int po(ListNode head){
        if(head == null) return 1;
        int c = po(head.next);

        int tmp = (head.val + c)%10;
        c = (head.val+c)/10;
        head.val = tmp;

        return c;
    }
}

results matching ""

    No results matching ""