[LC 369]. Plus One Linked List

dummy head的用法:当作进位位。Create一个val为0的dummy head,从dummy起始,搜索不是9的最低位,将其值变为1,其后所有node的值变为0.

    public ListNode plusOne(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode i = dummy, j = dummy; // i: last not nine digit
        while (j != null) {
            if (j.val != 9) i = j;
            j = j.next;
        }
        i.val++;
        i = i.next;
        while (i != null) {
            i.val = 0;
            i = i.next;
        }
        
        return dummy.val == 0 ? dummy.next : dummy;
        
    }

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s