Java Stack Solution with Inline Explanation


  • 0
    R
    public ListNode plusOne(ListNode head) {
        // "Reverse" the digits through LIFO
        final Stack<ListNode> stack = new Stack<>();
        ListNode node = head;
        while (node != null) {
            stack.push(node);
            node = node.next;
        }
        // Process until no more carries occur
        boolean carry = true;
        int val;
        while (!stack.isEmpty() && carry) {
            node = stack.pop();
            val = node.val + 1;
            carry = val > 9;
            node.val = carry ? val - 10 : val;
        }
        // For cases of all 9's, we need an extra digit
        if (carry) {
            node = new ListNode(1);
            node.next = head;
            head = node;
        }
        return head;
    }

Log in to reply
 

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