Java 2 pointer iterative solution 1ms


  • 0
    M
    public class Solution {
        public ListNode plusOne(ListNode head) {
            if(head == null) return null;
            
            ListNode curr = head;
            
            int carry = 0;
            
            // get to the end of the list
            while(true) {
                if(curr.next == null) {
                    int valPlus1 = curr.val + 1;
                    curr.val = valPlus1 % 10;
                    carry = valPlus1 / 10;
                    break;
                } else {
                    curr = curr.next;
                }
            }
            
            while(carry != 0) {
                // if curr is at the head, then create a new node and change it's next to curr so it becomes the new head
                ListNode node;
                if(curr == head) {
                    node = new ListNode(0);
                    node.next = curr;
                    head = node;
                } else {
                    // curr is not the head, start from beginning of the list to find the node before current
                    node = head;
                }
                
                // find where curr is in the list
                while(node.next != curr) node = node.next;
                
                // see if there is a carry to move to the previous node
                carry = (node.val + 1) / 10;
                
                // add 1 to the current value
                node.val = (node.val + 1) % 10;
                
                curr = node;
            }
            
            return head;
        }
    }
    

Log in to reply
 

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