Skip to content
This repository was archived by the owner on Sep 22, 2021. It is now read-only.

Commit aa2d0a3

Browse files
committed
Merge two sorted linked list in js
1 parent 482ee01 commit aa2d0a3

3 files changed

Lines changed: 29 additions & 40 deletions

File tree

‎.idea/vcs.xml‎

Lines changed: 6 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Backtracking/CombinationSum.js‎

Lines changed: 0 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +0,0 @@
1-
/**
2-
* @param {number[]} candidates
3-
* @param {number} target
4-
* @return {number[][]}
5-
*/
6-
var combinationSum = function(candidates, target) {
7-
var result = [];
8-
9-
if (candidates == null || candidates.length === 0) {
10-
return result;
11-
};
12-
13-
var current = [];
14-
candidates.sort();
15-
16-
combinationSumHelper(candidates, target, 0, current, result);
17-
18-
return result;
19-
};
20-
21-
function combinationSumHelper(candidates, target, j, curr, result){
22-
if(target === 0){
23-
var temp = curr.slice();
24-
result.push(temp);
25-
return;
26-
}
27-
28-
for(var i=j; i<candidates.length; i++){
29-
if(target < candidates[i]) {
30-
return;
31-
}
32-
curr.push(candidates[i]);
33-
combinationSumHelper(candidates, target - candidates[i], i, curr, result);
34-
curr.pop();
35-
}
36-
}
37-
38-
const candidates = [2,3,6,7];
39-
const target = 7;
40-
console.log(combinationSum(candidates, target));
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
function mergeTwoSortedLists (l1, l2) {
2+
3+
let mergedLinkedListHead = { val : -1, next : null }; // create dummy node to get started
4+
let runner = mergedLinkedListHead;
5+
6+
while(l1 && l2) {
7+
if(l1.val > l2.val) {
8+
runner.next = l2;
9+
l2 = l2.next;
10+
} else {
11+
runner.next = l1;
12+
l1 = l1.next;
13+
}
14+
runner = runner.next;
15+
}
16+
17+
// l1 = 1->2->3, l2 = 10->20->30
18+
// In that case l1, will point to null and while loop will break
19+
// Simply point runner to l2. We do not have to add individual nodes
20+
runner.next = l1 || l2;
21+
22+
return mergedLinkedListHead.next;
23+
}

0 commit comments

Comments
 (0)