Question
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]
Algorithm
看的题解,有一个好的思路
最不好处理的是带9
的case,比如199 + 1 = 200,这里专门用一个指针记录最早9->0的位置。
slow
,fast
两个指针slow
:记录9
的位置fast
:正常遍历的指针
fast->val
等于9的时候,slow
不动fast->val
不等于9的时候,slow
移动到fast
处- 遍历结束,
slow
的值+1
,slow
后面的都归0
Code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* plusOne(ListNode* head) {
ListNode* slow = new ListNode(0);
slow->next=head;
ListNode* fast = head;
while(fast){
if (fast->val != 9){
slow = fast;
}
fast = fast->next;
}
slow->val += 1;
ListNode* tmp = slow->next;
while(tmp){
tmp->val = 0;
tmp = tmp->next;
}
return slow->next==head?slow:head;
}
};