Created
August 20, 2020 22:56
-
-
Save RP-3/def6160ee6026c7e6e1d28c128446c5e to your computer and use it in GitHub Desktop.
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
| // O(n) time, O(1) space | |
| var reorderList = function(head) { | |
| if(!head || !head.next) return; | |
| // split in half | |
| let [slow, fast, prev] = [head, head, null]; | |
| while(fast && fast.next){ | |
| prev = slow; | |
| slow = slow.next; | |
| fast = fast.next.next; | |
| } | |
| let backHalfHead = prev.next; | |
| prev.next = null; | |
| // reverse second half | |
| let [a, b] = [backHalfHead, backHalfHead.next]; | |
| a.next = null; | |
| while(b){ | |
| let tmp = b.next; | |
| b.next = a; | |
| a = b; | |
| b = tmp; | |
| } | |
| backHalfHead = a; | |
| // weave together | |
| [a, b] = [head, backHalfHead]; | |
| while(a && b){ | |
| let tmpA = a.next; | |
| let tmpB = b.next; | |
| a.next = b; | |
| b.next = tmpA || tmpB; | |
| a = tmpA; | |
| b = tmpB; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment