File tree Expand file tree Collapse file tree 1 file changed +43
-0
lines changed
Linked_List/369.Plus-One-Linked-List Expand file tree Collapse file tree 1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
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
+ };
You can’t perform that action at this time.
0 commit comments