Skip to content

Commit 7214a58

Browse files
authored
Create 369.Plus-One-Linked-List.cpp
1 parent 2008f6b commit 7214a58

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* plusOne(ListNode* head)
14+
{
15+
int carry = 0;
16+
dfs(head, carry);
17+
if (carry == 0)
18+
return head;
19+
else
20+
{
21+
ListNode* node = new ListNode(1);
22+
node->next = head;
23+
return node;
24+
}
25+
}
26+
27+
void dfs(ListNode* head, int& carry)
28+
{
29+
if (head==NULL)
30+
{
31+
carry = 1;
32+
return;
33+
}
34+
35+
dfs(head->next, carry);
36+
37+
int val = head->val + carry;
38+
carry = val / 10;
39+
head->val = val % 10;
40+
41+
// if (head->val==3) cout<<val<<endl;
42+
}
43+
};

0 commit comments

Comments
 (0)