I have a few classes to make a linked list of books. I am having a hard time alphabetically sorting each book and returning them all. I haven't found anything on SO related to sorting linked lists alphabetically in JavaScript specifically so hopefully this post example will be useful for others too. The sortList() function should sort the books alphabetically by their name and return them all so they can be console.log'd.
class Book {
constructor(element) {
this.element = element;
this.next = null;
}
}
class Books {
constructor() {
this.head = null;
this.size = 0;
}
add(element) { //adds a book
var node = new Book(element);
var current;
if (this.head == null) this.head = node;
else {
current = this.head;
while (current.next) {
current = current.next;
}
current.next = node;
}
this.size++;
}
insertAt(element, index) { //adds a book at the specified index
if (index < 0 || index > this.size)
return console.log("Please enter a valid index.");
else {
var node = new Book(element);
var curr, prev;
curr = this.head;
if (index == 0) {
node.next = this.head;
this.head = node;
} else {
curr = this.head;
var it = 0;
while (it < index) {
it++;
prev = curr;
curr = curr.next;
}
node.next = curr;
prev.next = node;
}
this.size++;
}
}
sortList() { //sorts the head alphabetically
var sortedList = new Books();
let current = this.head;
var array = new Set();
while (current != null) {
array.add(current);
current = current.link;
}
array.sort();
for (let i = array.length - 1; i >= 0; i--) {
sortedList.insertAt(new Book(array[i]), 0);
}
return sortedList;
}
}
var bookList = new Books();
bookList.add("abook1");
bookList.add("bbook2");
bookList.add("cbook3");
bookList.add("dbook4");
bookList.add("ebook5");
bookList.add("fbook6");
bookList.add("gbook7");
bookList.add("hbook8");
console.log(bookList.sortList()); //prints out the sorted bookList