369. Plus One Linked List
Problem:
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->4Analysis:
Two pointers. i reaches the last node before 9, j reaches the tail node.
1-> 2 -> 4 -> 9 -> null
i j
We can set i.val++, and set node after i's val to 0.
One corner case is the list starts with 9 and only has 9. like 9 -> 9->null. So we start checking 9 from dummy.
Solution:
class Solution { public ListNode plusOne(ListNode head) { if (head == null) return null; ListNode dummy = new ListNode(0); dummy.next = head; ListNode i = dummy; ListNode j = head; while (j != null) { if (j.val != 9) { i = j; } j = j.next; } i.val += 1; i = i.next; while (i != null) { i.val = 0; i = i.next; } return dummy.val == 0 ? dummy.next : dummy; } }
评论
发表评论