Java Concise using Stack


  • 0
    public class Solution {
        public ListNode plusOne(ListNode head) {
            Stack<ListNode> stack = new Stack<>();
            ListNode curr = head;
            while (curr != null) {
                stack.push(curr);
                curr = curr.next;
            }
            int carry = 1;  
            while (!stack.isEmpty() && carry > 0) {  
                curr = stack.pop();
                curr.val++;
                carry = curr.val / 10;
                curr.val %= 10;
            }
            if (carry > 0) {
                curr = new ListNode(1);
                curr.next = head;
                head = curr;
            }
            return head;
        }
    }
    

Log in to reply
 

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