Recursive using Wrapper class


  • 0
    C
    import java.util.List;
    import java.util.regex.Pattern;
    
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public class Wrapper{
            ListNode node;
            boolean ifCarry = false;
            public Wrapper (ListNode node) {
                this.node = node;
            }
        }
        public ListNode plusOne(ListNode head) {
            // recursive
            Wrapper res = helper(new Wrapper(head));
            if (res == null) 
                return head;
            if (res.ifCarry) {
                ListNode resNode = new ListNode(1);
                resNode.next = res.node;
                return resNode;
            }
            return res.node;
        }
        private Wrapper helper (Wrapper head) {
            if (head.node == null) {
                return null;
            }
            Wrapper n = helper(new Wrapper(head.node.next));
            if (n == null || n.ifCarry) {
                head.node.val += 1;
                if (head.node.val > 9)
                    head.ifCarry = true;
                head.node.val = head.node.val % 10;
            }
            return head;
        }
    
    }
    

Log in to reply
 

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