I am trying to partition a linkedlist but can't seem to get it to work when there are no elements less than the current value that you are looking at. the idea is based on the val, items less than the parameter value go to the left in the linkedlist and items greater than the parameter value go to the right. I changed some of the conditions for adding to the "greaterThan" and "lessThan" linkedlists, but then it would stop working if the item was in the middle. What am i missing? Have been stuck on this for quite a bit. the most relevant function here is the "partition" function, everything else is a helper.
var LinkedList = function () {
this.head = null;
this.tail = null;
};
LinkedList.prototype.makeNode = function (val) {
var node = {};
node.val = val;
node.next = null;
return node;
};
LinkedList.prototype.partition = function (val) {
var lesserThanVal = new LinkedList();
var greaterThanVal = new LinkedList();
var iterator = this.head;
while (iterator) {
if (iterator.val < val) {
lesserThanVal.addToTail(iterator.val);
} else if (iterator.val >= val) {
greaterThanVal.addToTail(iterator.val);
}
iterator = iterator.next;
}
//now merge them.
if (lesserThanVal.head === null) {
console.log("LESSER IS NULL")
return greaterThanVal;
}
if (greaterThanVal.head === null) {
console.log("GREATER IS NULL")
return lesserThanVal;
} else {
//merge
var pointer = lesserThanVal.head;
while (pointer.next) {
pointer = pointer.next;
}
pointer.next = greaterThanVal.head;
lesserThanVal.tail = greaterThanVal.tail;
console.log("SHOULD BE 9", lesserThanVal.head.next.next);
return lesserThanVal;
}
};
LinkedList.prototype.addToTail = function (value) {
var newTail = this.makeNode(value);
if (!this.head) {
this.head = newTail;
}
if (this.tail) {
this.tail.next = newTail;
}
this.tail = newTail;
};
Tests:
var list = new LinkedList();
list.addToTail(8);
list.addToTail(4);
list.addToTail(5);
list.addToTail(9);
console.log(list);
var partitionedList = list.partition(8);
returns { head: { val: 4, next: { val: 5, next: [8...] } },
tail: { val: 9, next: null } }
var partitionedList = list.partition(4);
returns { head: { val: 8, next: { val: 4, next: [5...] } },
tail: { val: 9, next: null } }
var partitionedList = list.partition(9);
returns { head: { val: 8, next: { val: 4, next: [{5...}] } },
tail: { val: 9, next: null } }
var partitionedList = list.partition(5);
returns { head: { val: 4, next: { val: 8, next: [{5....}] } },
tail: { val: 9, next: null } }
console.log(partitionedList);
fiddle: https://jsfiddle.net/e76vcwtp/