leetcode369- Plus One Linked List- medium

Posted jasminemzy

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode369- Plus One Linked List- medium相关的知识,希望对你有一定的参考价值。

Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.

You may assume the integer do not contain any leading zero, except the number 0 itself.

The digits are stored such that the most significant digit is at the head of the list.

Example:

Input:
1->2->3

Output:
1->2->4

 

和+1数组有点像,关键要知道最多只要记录一串X9999就够了,前面的都是浮云,如果出现小于9的数字就相当于屏障,再也影响不到它之前的了。

最后这串被记录下来的,每个digit都做 digit = (digit + 1) % 10的操作。如果最前面的X也是9,那说明其实你整串肯定都是9999999,否则如89999不可能会最后存下来的第一个是9的。这个时候特殊还要再加一个1在最前头。

关于怎么记录有两种方法:

1.O(n) 空间:用一个stack。存下来后一个个吐回去

2.O(1)空间:用一个ListNode,只要记下最前面的X即可, 因为可以调用next不断向后遍历。

细节:1.小心99999多加一个点的问题。

 

实现1,用stack:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode plusOne(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        while (head != null) {
            if (head.val != 9) {
                stack.clear();
            }
            stack.push(head);
            head = head.next;
        }
        ListNode crt = null;
        while (!stack.isEmpty()) {
            crt = stack.pop();
            crt.val = (crt.val + 1) % 10;
        }
        if (crt != null && crt.val == 0) {
            ListNode newN = new ListNode(1);
            newN.next = dummy.next;
            dummy.next = newN;
        }
        return dummy.next;
    }
}

 

实现2,用指针:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode plusOne(ListNode head) {
        Stack<ListNode> stack = new Stack<>();
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode change = head;
        
        // find the start point of those node that need change
        while (head != null) {
            if (head.val != 9) {
                change = head;
            }
            head = head.next;
        }
        
        // for the special case of 99999999...
        if (change.val == 9) {
            ListNode newN = new ListNode(1);
            newN.next = change;
            dummy.next = newN;
        }
        
        // make the add one change
        while (change != null) {
            change.val = (change.val + 1) % 10;
            change = change.next;
        }
        
        return dummy.next;
    }
}

 

以上是关于leetcode369- Plus One Linked List- medium的主要内容,如果未能解决你的问题,请参考以下文章

leetcode369- Plus One Linked List- medium

369. Plus One Linked List

369. Plus One Linked List

369. Plus One Linked List

java 369. Plus One Linked List(Recursive).java

java 369. Plus One Linked List(Recursive).java