Clear Java 2ms solution using a stack


  • 0
    public class Solution {
    public ListNode plusOne(ListNode head) {
        ListNode curr = head;
        Stack<ListNode> stk = new Stack<>();
        int carry = 1;
        while(curr!=null){
            stk.push(curr);
            curr = curr.next;
        }
        while(stk.empty()==false&&carry!=0){
            ListNode temp = stk.peek();
            temp.val += 1;
            if(temp.val==10){
                temp.val=0;
                carry = 1;
            }
            else{
                carry = 0;
            }
            stk.pop();
        }
        if(carry==1){
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            dummy.val = 1;
            return dummy;
        }
        else{
            return head;
        }
    }
    }

Log in to reply
 

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