-
Notifications
You must be signed in to change notification settings - Fork 28
/
Plus_One_Linked_List.cpp
45 lines (44 loc) · 1.14 KB
/
Plus_One_Linked_List.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
void plusOneRecur(ListNode* curr, ListNode* head, ListNode* sentinel, int& carry) {
if(!curr->next) {
curr->val++;
carry = curr->val / 10;
curr->val %= 10;
if(curr == head) {
if(carry > 0) {
sentinel->val += carry;
}
}
return;
}
plusOneRecur(curr->next, head, sentinel, carry);
if(!carry) {
return;
}
curr->val += carry;
carry = curr->val / 10;
curr->val %= 10;
if(curr == head) {
if(carry > 0) {
sentinel->val += carry;
}
}
}
public:
ListNode* plusOne(ListNode* head) {
if(!head) return head;
ListNode* sentinel = new ListNode(0);
sentinel->next = head;
int carry = 0;
plusOneRecur(head, head, sentinel, carry);
return ((sentinel->val > 0) ? sentinel : head);
}
};