【发布时间】:2021-12-07 11:53:36
【问题描述】:
我有几门课来制作书的链接列表。我很难按字母顺序对每本书进行排序并将它们全部归还。我还没有找到任何与在 JavaScript 中按字母顺序排序链接列表相关的内容,因此希望这个帖子示例对其他人也有用。 sortList() 函数应该按书籍名称的字母顺序对书籍进行排序,然后将它们全部返回,这样它们就可以成为 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
【问题讨论】:
-
不要把你的答案放在问题中。我回滚了你的最新更改。答案(仅)属于答案部分。这就是 Stack Overflow 的工作原理。
标签: javascript class sorting linked-list