Given a non-negative number represented as a singly linked list of digits, plus one to the number.
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. 需要考虑limit case,极限的情况,这个题出现的变化!!!比如,input: 9->9, output: 1->0->0
2. 添加dummy node, 用recursive. 因为,recursive把链表看成一层一层的,而且可以先处理最底层的数据,对链表最底层就是个位,所以先处理个位,就是我们需要的!
bool helper(ListNode* head){
if(head==NULL){
return 1;
}
int carry=helper(head->next);
int sum=head->val+carry;
head->val=sum%10;
return sum>9;
}
ListNode* plusOne(ListNode* head) {
bool carry=helper(head);
if(carry){
ListNode* dummy=new ListNode(1);
dummy->next=head;
return dummy;
}
return head;
}