File tree 2 files changed +61
-0
lines changed
2 files changed +61
-0
lines changed Original file line number Diff line number Diff line change @@ -319,6 +319,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
319
319
320
320
- [ Add Two Numbers] ( src/linked-list/add-two-numbers.js )
321
321
- [ Merge K Sorted Lists] ( src/linked-list/merge-k-sorted-lists.js )
322
+ - [ Plus One Linked List] ( src/linked-list/plus-one-linked-list.js )
322
323
323
324
### Dynamic Programming
324
325
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Plus One Linked List
3
+ *
4
+ * Given a non-negative integer represented as non-empty a singly linked list of digits, plus one to the integer.
5
+ *
6
+ * You may assume the integer do not contain any leading zero, except the number 0 itself.
7
+ *
8
+ * The digits are stored such that the most significant digit is at the head of the list.
9
+ *
10
+ * Example:
11
+ *
12
+ * Input:
13
+ * 1->2->3
14
+ *
15
+ * Output:
16
+ * 1->2->4
17
+ */
18
+
19
+ /**
20
+ * Definition for singly-linked list.
21
+ * function ListNode(val) {
22
+ * this.val = val;
23
+ * this.next = null;
24
+ * }
25
+ */
26
+
27
+ /**
28
+ * @param {ListNode } head
29
+ * @return {ListNode }
30
+ */
31
+ const plusOne = head => {
32
+ if ( dfs ( head ) === 0 ) {
33
+ return head ;
34
+ }
35
+
36
+ const newHead = new ListNode ( 1 ) ;
37
+ newHead . next = head ;
38
+ return newHead ;
39
+ } ;
40
+
41
+ /**
42
+ * Returns the carry value
43
+ */
44
+ const dfs = node => {
45
+ if ( node === null ) {
46
+ return 1 ;
47
+ }
48
+
49
+ const carry = dfs ( node . next ) ;
50
+
51
+ if ( carry === 0 ) {
52
+ return 0 ;
53
+ }
54
+
55
+ const val = node . val + carry ;
56
+ node . val = val % 10 ;
57
+ return Math . floor ( val / 10 ) ;
58
+ } ;
59
+
60
+ export { plusOne } ;
You can’t perform that action at this time.
0 commit comments