Concise Java iterative solution


  • 0
    F

    The idea is based on oceaniatt's solution.

    public ListNode plusOne(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode runner = dummy;
        ListNode pointer = dummy; //from right to left, find the first digit that is not 9;
        
        while(runner.next != null) {
            runner = runner.next;
            if(runner.val != 9) pointer = runner;
        }
        
        pointer.val = pointer.val + 1;
        runner = pointer.next;
        while(runner != null) {
            runner.val = 0;
            runner = runner.next;
        }
        
        return pointer == dummy? dummy : head;
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.