Last active
October 11, 2018 22:53
-
-
Save lienista/3b0dd1ea4260b5ecc2bf2e3abc4edfe5 to your computer and use it in GitHub Desktop.
Leetcode 86. Partition List - Given a linked list and a value x, partition it such that all nodes less than x come before nodes greater than or equal to x. You should preserve the original relative order of the nodes in each of the two partitions.
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
| const partition = (head, x) => { | |
| if(head === null) return head; | |
| let beforeStart = null, | |
| beforeEnd = null, | |
| afterStart = null, | |
| afterEnd = null; | |
| while(head) { | |
| let next = head.next; | |
| head.next = null; | |
| if(head.val < x) { | |
| if(!beforeStart) { | |
| beforeStart = head; | |
| beforeEnd = beforeStart; | |
| } else { | |
| beforeEnd.next = head; | |
| beforeEnd = head; | |
| } | |
| } else { | |
| if(!afterStart) { | |
| afterStart = head; | |
| afterEnd = afterStart; | |
| } else { | |
| afterEnd.next = head; | |
| afterEnd = head; | |
| } | |
| } | |
| head = next; | |
| } | |
| if(!beforeStart) { | |
| return afterStart; | |
| } | |
| beforeEnd.next = afterStart; | |
| return beforeStart; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment