@cocacola-lover/knight_path_finder
Version:
Iterative path finding Algorithms for knight on a chessboard
66 lines • 1.94 kB
JavaScript
class ListItem {
constructor(value) {
this.next = null;
this.value = value;
}
}
export default class OrderedLinkedList {
constructor(compareFunction, arr = []) {
this.start = null;
const checkForSorted = (compareFunction, arr = []) => {
for (let i = 0; i < arr.length - 1; i++) {
if (compareFunction(arr[i], arr[i + 1]) > 0)
return false;
}
return true;
};
const readInArray = (arr) => {
this.start = new ListItem(arr[0]);
let pos = this.start;
for (let i = 1; i < arr.length; i++) {
const newItem = new ListItem(arr[i]);
pos.next = newItem;
pos = newItem;
}
};
this.compareFunction = compareFunction;
if (arr.length === 0)
return;
if (!checkForSorted(this.compareFunction, arr))
arr = arr.sort(this.compareFunction);
readInArray(arr);
}
isEmpty() { return this.start === null; }
shift() {
if (this.start === null)
return undefined;
let ans = this.start.value;
this.start = this.start.next;
return ans;
}
pickIn() {
if (this.start === null)
return undefined;
return this.start.value;
}
add(a) {
if (this.start === null) {
this.start = new ListItem(a);
return;
}
let pos = this.start;
let before = null;
while (pos !== null && this.compareFunction(a, pos.value) > 0) {
before = pos;
pos = pos.next;
}
const newItem = new ListItem(a);
if (before !== null)
before.next = newItem;
else {
this.start = newItem;
}
newItem.next = pos;
}
}
//# sourceMappingURL=ordered_linked_list.js.map