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->4plus one的题,解法1:
找到从右向左的第一个不为9的数,将其++,从这个节点开始向右的所有节点都设为0,因为后面的全都进了位,eg. 1->2->9->9,第一个不为9的数是2,则答案是1->3->0->0,再比如1->2->3第一个不为9的数是3,答案是1->2->4。
如果没有不为9的数,说明所有数都是9则需要多开一个节点0,加在head前面,这样把第一个节点0++,其他节点都设为0,eg,9->9->9,结果为1->0->0->0.
代码如下:
/**
* 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 *cur = head, *right = NULL;
while (cur) {
if (cur->val != 9) right = cur;
cur = cur->next;
}
if (right == NULL) {
right = new ListNode(0);
right->next = head;
head = right;
}
right->val++;
cur = right->next;
while (cur) {
cur->val = 0;
cur = cur->next;
}
return head;
}
};
解法2:
先把list reverse,然后做操作,然后在reverse回来:
class Solution {
public:
ListNode* plusOne(ListNode* head) {
if (head == NULL) return head;
ListNode* new_head = reverse(head);
ListNode *cur = new_head, *pre = cur;
int carry = 1;
while(cur) {
pre = cur;
int t = cur->val + carry;
cur->val = t % 10;
carry = t / 10;
if (carry == 0) break;
cur = cur->next;
}
if (carry) pre->next = new ListNode(1);
return reverse(new_head);
//return head;
}
ListNode* reverse(ListNode *head) {
if (!head) return head;
ListNode *dummy = new ListNode(-1), *cur = head;
dummy->next = head;
while (cur->next) {
ListNode *t = cur->next;
cur->next = t->next;
t->next = dummy->next;
dummy->next = t;
}
return dummy->next;
}
};