0ms Java LL Reverse-based Solution


  • 0
    O
    public ListNode plusOne(ListNode head) {
            return reverseAndAdd(reverseAndAdd(head, 0), 1);
        }
    
        private ListNode reverseAndAdd(ListNode head, int carry) {
            ListNode prev = null;
            ListNode iter = head;
            while (iter != null) {
                iter.val += carry;
                if (iter.val > 9) {
                    iter.val = 0;
                    carry = 1;
                } else {
                    carry = 0;
                }
                ListNode next = iter.next;
                iter.next = prev;
                prev = iter;
                iter = next;
            }
            ListNode newHead;
            if (carry == 1) {
                newHead = new ListNode(1);
                newHead.next = prev;
            } else {
                newHead = prev;
            }
            return newHead;
        }
    

Log in to reply
 

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