# [LeetCode] 369. Plus One Linked List 链表加一运算

2021年09月15日 阅读数：1

Given a non-negative number represented as a singly linked list of digits, plus one to the number.html

The digits are stored such that the most significant digit is at the head of the list.java

Example:node

```Input:
1->2->3

Output:
1->2->4```

Java:post

```public ListNode plusOne(ListNode head) {

ListNode p=h2;

while(p!=null){
if(p.val+1<=9){
p.val=p.val+1;
break;
}else{
p.val=0;
if(p.next==null){
p.next = new ListNode(1);
break;
}
p=p.next;
}
}

return reverse(h2);
}

ListNode p2=p1.next;
while(p2!=null){
ListNode t = p2.next;
p2.next=p1;
p1=p2;
p2=t;
}

return p1;
}　　```

Python:url

```# Time:  O(n)
# Space: O(1)

class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None

# Two pointers solution.
class Solution(object):
"""
:rtype: ListNode
"""
return None

dummy = ListNode(0)

while right.next:
if right.val != 9:
left = right
right = right.next

if right.val != 9:
right.val += 1
else:
left.val += 1
right = left.next
while right:
right.val = 0
right = right.next

return dummy if dummy.val else dummy.next
```

Python:htm

```# Time:  O(n)
# Space: O(1)
class Solution2(object):
"""
:rtype: ListNode
"""
dummy = ListNode(0)
while curr:
dummy.next, curr.next, curr = curr, dummy.next, curr.next
return dummy.next

while curr and carry:
curr.val += carry
carry = curr.val / 10
curr.val %= 10
if carry and curr.next is None:
curr.next = ListNode(0)
curr = curr.next

C++:blog

```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;
}
};
```

C++: Recursiveget

```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;
}
};
```

[LeetCode] 66. Plus One 加一