File tree Expand file tree Collapse file tree 1 file changed +15
-2
lines changed
chapter02/2.4 - Partition Expand file tree Collapse file tree 1 file changed +15
-2
lines changed Original file line number Diff line number Diff line change @@ -8,8 +8,10 @@ var partition = function(head, partition) {
88 // and attach nodes with values less than partition value to the left
99 // and nodes with vallues more than partition value to the right
1010 var left ;
11+ var middle ;
1112 var right ;
1213 var currLeft = null ;
14+ var currMiddle = null ;
1315 var currRight = null ;
1416
1517 var node = head ;
@@ -22,6 +24,14 @@ var partition = function(head, partition) {
2224 currLeft . next = node ;
2325 currLeft = currLeft . next ;
2426 }
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+ }
2535 } else {
2636 if ( currRight === null ) {
2737 right = node ;
@@ -34,13 +44,16 @@ var partition = function(head, partition) {
3444 node = node . next ;
3545 }
3646 currRight . next = null ;
37- currLeft . next = right ; // connect two partitions together
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 ;
3851 return left ; // return head of new linkedList
3952} ;
4053
4154/* TESTS */
4255// Input: 3 -> 5 -> 8 -> 5 -> 10 -> 2 -> 1 [partition = 5]
43- // Output: 3 -> 2 -> 1 -> 5 -> 8 -> 5 -> 10
56+ // Output: 3 -> 2 -> 1 -> 5 -> 5 -> 8 -> 10
4457
4558var printList = function ( a ) {
4659 while ( a !== null ) {
You can’t perform that action at this time.
0 commit comments