链表数加上1
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
ListNode* plusOne(ListNode* head) {
auto dummy = new ListNode(0);
dummy->next = head;
// 找最后一个!=9(不进位)的位置
ListNode *found;
for (auto p = dummy; p; p = p->next) {
if (p->val != 9) found = p;
}
// found位置加1,后面位置全变0
found->val += 1;
for (auto p = found->next; p; p = p->next) {
p->val = 0;
}
// 如果dummy后全是9,found=dummy,dummy->val==1
if (dummy->val != 0) return dummy;
auto ans = dummy->next;
delete dummy;
return ans;
}