# 369. Plus One Linked List

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]
``````

``````class Solution {
public:
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);
}
ListNode *dummy = new ListNode(-1), *cur = head;
while (cur->next) {
ListNode *t = cur->next;
cur->next = t->next;
t->next = dummy->next;
dummy->next = t;
}
return dummy->next;
}
};
``````

``````class Solution {
public:
if (carry == 1) {
ListNode *res = new ListNode(1);
return res;
}
}
int helper(ListNode *node) {
if (!node) return 1;
int carry = helper(node->next);
int sum = node->val + carry;
node->val = sum % 10;
return sum / 10;
}
};
``````

``````class Solution {
public:
ListNode *cur = head, *right = NULL;
while (cur) {
if (cur->val != 9) right = cur;
cur = cur->next;
}
if (!right) {
right = new ListNode(0);
}
++right->val;
cur = right->next;
while (cur) {
cur->val = 0;
cur = cur->next;
}
}
};
``````

``````class Solution {
public:
stack<ListNode*> s;
while (cur) {
s.push(cur);
cur = cur->next;
}
int carry = 1;
while (!s.empty() && carry) {
ListNode *t = s.top(); s.pop();
int sum = t->val + carry;
t->val = sum % 10;
carry = sum / 10;
}
if (carry) {
}
}
};
``````

Plus One

https://leetcode.com/discuss/111165/2-accepted-java-solution

https://leetcode.com/discuss/111205/simple-solution-use-recursion

https://leetcode.com/discuss/111157/9-lines-recursive-without-helper

https://leetcode.com/discuss/111155/java-stack-solution-with-inline-explanation

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation