Two-Pointers Java Solution: O(n) time, O(1) space


  • 24
    X
    public class Solution {
        public ListNode plusOne(ListNode head) {
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            ListNode i = dummy;
            ListNode j = dummy;
    
            while (j.next != null) {
                j = j.next;
                if (j.val != 9) {
                    i = j;
                }
            }
            // i = index of last non-9 digit
        
            i.val++;
            i = i.next;
            while (i != null) {
                i.val = 0;
                i = i.next;
            }
            
            if (dummy.val == 0) return dummy.next;
            return dummy;
        }
    }

  • 0
    H

    This is a great solution! No need to reverse!


  • 0

    Great solution for this problem!


Log in to reply
 

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