Java solution (reverse the list).


  • 0
    C
    public ListNode plusOne(ListNode head) {
        // reverse the list first 
        ListNode node = reverse(head);
        int carry = 1;
        head = node; 
        while (node != null) {
            int tmp = node.val+carry;
            carry = tmp / 10;
            node.val = tmp % 10;
            node = node.next;
        }
        node = reverse(head);
        // add one more node
        if (carry == 1) {
            head = new ListNode(1);
            head.next = node;
            return head;
        }
        return node;
    }
    
    private ListNode reverse(ListNode head) {
        ListNode node = null;
        while (head != null) {
            ListNode nxt = head.next;
            head.next = node;
            node = head;
            head = nxt;
        }
        return node;
    }

Log in to reply
 

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