JAVA Reverse + Plus + Reverse


  • 0
    Y
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode plusOne(ListNode head) {
            if(head == null)
                return head;
            ListNode pre = reverse(head);
            head = pre.next;
            boolean plus = true;
            while(pre.next != null && plus){
                if(pre.next.val == 9)
                    pre.next.val = 0;
                else{
                    pre.next.val += 1;
                    plus = false;
                }
                pre = pre.next;
            }
            if(plus)
                pre.next = new ListNode(1);
            return reverse(head).next;
        }
        
        public ListNode reverse(ListNode head){
            ListNode pre = new ListNode(0);
            pre.next = head;
            while(head.next != null){
                ListNode tmp = pre.next;
                pre.next = head.next;
                head.next = head.next.next;
                pre.next.next = tmp;
            }
            
            return pre;
        }
    }

Log in to reply
 

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