Created
November 16, 2018 17:11
-
-
Save leonardovff/aeb8ca7b7e145131e010d2f0f62f0481 to your computer and use it in GitHub Desktop.
Merge and sort two different javascript list
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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