AC Stack solution


  • 0
    J
    public ListNode plusOne(ListNode head) {
            Stack<ListNode> stack = new Stack<ListNode>();
            ListNode node = head;
            while (node != null) {
                stack.push(node);
                node = node.next;
            }
            int extra = 1;
            while (!stack.isEmpty()) {
                ListNode current = stack.pop();
                if (extra != 0) {
                    int sum = current.val + extra;
                    current.val = sum % 10;
                    extra = sum / 10;
                }
            }
            if (extra != 0) {
                node = new ListNode(extra);
                node.next = head;
                return node;
            }
            return head;
        }

Log in to reply
 

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