Skip to content

Commit 213c151

Browse files
authored
Merge pull request #283 from jeantimex/plus-one-linked-list
Plus One Linked List
2 parents 7e03062 + 37f9bef commit 213c151

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -319,6 +319,7 @@ A collection of JavaScript problems and solutions for studying algorithms.
319319

320320
- [Add Two Numbers](src/linked-list/add-two-numbers.js)
321321
- [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)
322323

323324
### Dynamic Programming
324325

+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
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 };

0 commit comments

Comments
 (0)