JAVA 1ms solution using Stack


  • 0
    I

    It uses stack to record each most significant node, then pop them and add one. It uses carry to handle special cases like 9->9->9.

    public ListNode plusOne(ListNode head) {
            Stack<ListNode> st = new Stack<>();
            ListNode cur = head;
            while(cur!=null){
                st.push(cur);
                cur=cur.next;
            }
            int carry=1;
            while(!st.isEmpty()){
                ListNode now = st.pop();
                now.val+=carry;
                if(now.val>9){
                now.val=0;
                carry=1;
                }
                else {
                    carry=0;
                    break;
                }
            }
            if(carry==1){
            ListNode newhead = new ListNode(1);
            newhead.next=head;
            head=newhead;
            }
            return head;
        }
    

Log in to reply
 

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