Skip to content

Instantly share code, notes, and snippets.

@leonardovff
Created November 16, 2018 17:11
Show Gist options
  • Save leonardovff/aeb8ca7b7e145131e010d2f0f62f0481 to your computer and use it in GitHub Desktop.
Save leonardovff/aeb8ca7b7e145131e010d2f0f62f0481 to your computer and use it in GitHub Desktop.
Merge and sort two different javascript list
// Definition for singly-linked list:
// function ListNode(x) {
// this.value = x;
// this.next = null;
// }
let last = false,
unified = false;
function mergeTwoLinkedLists(l1, l2, first = true) {
if(!l1){
if(!l2){
return l1;
}
return mergeTwoLinkedLists(l2, null);
}
if(l1 && !l1.next && l2){
l1.next = l2;
l2 = null;
unified = true;
}
if(l1 && l1.next) {
if(l1.value <= l1.next.value) {
mergeTwoLinkedLists(l1.next, l2, false);
}
}
if(!l2 && l1 && !l1.next){
last = true;
}
if(l1 && l1.next && l1.value > l1.next.value) {
l1.value += l1.next.value;
l1.next.value = l1.value - l1.next.value;
l1.value = l1.value - l1.next.value;
}
if(first && !last){
mergeTwoLinkedLists(l1, (unified ? null : l2));
}
return l1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment