| 4 | }; |
| 5 | |
| 6 | var partition = function(head, partition) { |
| 7 | // approach is to create left and right threads |
| 8 | // and attach nodes with values less than partition value to the left |
| 9 | // and nodes with vallues more than partition value to the right |
| 10 | var left; |
| 11 | var middle; |
| 12 | var right; |
| 13 | var currLeft = null; |
| 14 | var currMiddle = null; |
| 15 | var currRight = null; |
| 16 | |
| 17 | var node = head; |
| 18 | while (node !== null) { |
| 19 | if (node.value < partition) { |
| 20 | if (currLeft === null) { |
| 21 | left = node; |
| 22 | currLeft = left; |
| 23 | } else { |
| 24 | currLeft.next = node; |
| 25 | currLeft = currLeft.next; |
| 26 | } |
| 27 | } else if (node.value === partition) { |
| 28 | if (currMiddle === null) { |
| 29 | middle = node; |
| 30 | currMiddle = middle; |
| 31 | } else { |
| 32 | currMiddle.next = node; |
| 33 | currMiddle = currMiddle.next; |
| 34 | } |
| 35 | } else { |
| 36 | if (currRight === null) { |
| 37 | right = node; |
| 38 | currRight = right; |
| 39 | } else { |
| 40 | currRight.next = node; |
| 41 | currRight = currRight.next; |
| 42 | } |
| 43 | } |
| 44 | node = node.next; |
| 45 | } |
| 46 | currRight.next = null; |
| 47 | // connect the left values with those matching the partition value |
| 48 | currLeft.next = middle; |
| 49 | // connect the middle with the right partitions |
| 50 | currMiddle.next = right; |
| 51 | return left; // return head of new linkedList |
| 52 | }; |
| 53 | |
| 54 | /* TESTS */ |
| 55 | // Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition = 5] |