Last active
December 12, 2015 12:19
-
-
Save charlespunk/4770806 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
| Write code to partition a linked list around a value x, such that all nodes less than x come before all nodes greater than or equal to x. |
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
| public static void partitionList(Node root, int x){ | |
| Node bigger = null; | |
| Node smaller = null; | |
| while(root != null){ | |
| if(root.value >= x){ | |
| if(bigger == null) bigger = root; | |
| else{ | |
| bigger.next = root; | |
| bigger = root; | |
| } | |
| } | |
| else{ | |
| if(smaller == null) smaller = root; | |
| else{ | |
| root.next = smaller; | |
| smaller = root; | |
| } | |
| } | |
| } | |
| if(bigger == null || smaller == null) return (bigger != null)? bigger : smaller; | |
| else{ | |
| bigger.next = smaller; | |
| return bigger; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment