LeetCode 369. Plus One Linked List

Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
Input: [1,2,3]
Output: [1,2,4]

idea:
the one i can think of is reverse add one and reverse back.
so i implemented with this:

class Solution {
    public ListNode plusOne(ListNode head) {
        reverse(head);
        ListNode p = head;
        while (p != null) {
            System.out.println(p.val);
            p = p.next;
        }
        ListNode cur = head;
        while (cur.next != null && cur.val == 9) {
            cur.val = 0;
            
            cur = cur.next;
            
        }
        if (cur.next == null) {
            if (cur.val == 9) {
                 cur.val = 0;
                cur.next = new ListNode(1);
            } else {
                cur.val += 1;
            }
        } else {
            if (cur.val == 9) {
                cur.val = 0;
                cur.next.val += 1; 
            } else {
                cur.val += 1;
            }
        }
        return reverse(head);
        
        
    }
    
    private ListNode reverse(ListNode head) {
        if (head == null || head.next == null) return null;
        
        ListNode dummy = new ListNode();
        dummy.next = head;
        ListNode pre = dummy;
        ListNode cur = head;
        while (cur.next != null) {
            ListNode temp = cur.next;
            cur.next = temp.next;
            temp.next = pre.next;
            pre.next = temp;
        }
        
        
        return dummy.next;
    } 
}

但是这种方法不太行 reverse之后 head不再是原来的head了

其实这道题目没有那么麻烦 就是添加一个dummy node 然后就是为了处理999变为1000的情况的。
this problem is actually easy, just thinking straight.

class Solution {
    public ListNode plusOne(ListNode head) {
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode i = dummy;
        ListNode j = dummy;
        
        while (j.next != null) {
            j = j.next;
            if (j.val != 9) {
                i = j; 
            }
        } //after this while statement, i will be placed to the position of the last non 9 at, and j will place at the the last position, in this case, all the numbers between (i, j) exclusively will be 9
        
        if (j.val != 9) { //then there is not need for i change into i.val+1
            j.val++;
        } else { //if the val in j is 9
            i.val++; //then
            i = i.next; //
            while (i != null) {
                i.val = 0;
                i = i.next;
            }
        }
        
        if (dummy.val == 0) { //that means the value of dummy is not changed, so that's we need to return dummy.next, else we return dummy
            return dummy.next;
        }
        return dummy; //the value of dummy node will be 1 so we will return whole
        
    }
    
    
}
posted @ 2020-11-20 01:51  EvanMeetTheWorld  阅读(17)  评论(0)    收藏  举报