Java O(n) solution


  • 0
    M
    public class Solution {
        public ListNode plusOne(ListNode head) {
            if(head==null) return head;
            int start = -10, index=0;
            for(ListNode p=head; p!=null; p=p.next){
                if(p.val==9){
                    p.val = 0;
                } else { // p.val<9
                    start = index-1;
                    p.val++;
                } 
                index++;
            }
            if(start==-10){
                ListNode newHead = new ListNode(1);
                newHead.next= head;
                return newHead;
            }
            index = 0;
            for(ListNode p=head; p!=null; p=p.next){
                if(index>start)
                    break;
                if(p.val==0) p.val = 9;
                else p.val--;
                index++;
            }
            return head;
        }
    }
    

Log in to reply
 

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