我有幾門課來制作書的鏈接串列。我很難按字母順序排列每本書并將它們全部歸還。我還沒有找到任何與在 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("book1");
bookList.add("book2");
bookList.add("book3");
bookList.add("book4");
bookList.add("book5");
bookList.add("book6");
bookList.add("book7");
bookList.add("book8");
console.log(bookList.sortList()); //prints out the sorted bookList
uj5u.com熱心網友回復:
您可以通過檢查節點和下一個節點來更改喜歡串列中的值。如有必要,交換值并從頭開始再次比較。
此方法采用比較函式,該函式使用三路比較,回傳值小于零、零或大于零,具體取決于順序。
const
compareString = (a, b) => a.localeCompare(b);
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 ;
}
sortList() {
let current = this.head;
while (current.next) {
if (compareString(current.element, current.next.element) > 0) { // swap
[current.element, current.next.element] = [current.next.element, current.element];
current = this.head;
continue;
}
current = current.next;
}
return this;
}
}
var bookList = new Books();
bookList.add("ac");
bookList.add("ab");
bookList.add("cc");
bookList.add("bb");
bookList.add("aa");
bookList.add("dd");
bookList.add("ba");
bookList.add("bc");
console.log(bookList.sortList()); //prints out the sorted bookList
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/327267.html
標籤:javascript 班级 排序 链表
下一篇:Python-串列-字串值更改
