javascript - 如何在 javascript 中按字母顺序打印此列表?
问题描述
我想按字母顺序对这个链表进行排序。这是一个家庭作业。经过广泛的研究,我没有发现任何有帮助的东西,所以希望这里有人可以。这是我第一次在 stackoverflow 上发帖,希望我做得对。
提前致谢。
console.log("*********** Section: 2 ***********");
console.log("Sorted Book List");
class Node {
constructor(data, next = null) {
this.data = data;
this.next = next;
}
}
class LinkedList {
constructor() {
this.head = null;
}
printList() {
if (!this.head) {
return;
}
let node = this.head;
let str = "";
while (node) {
str += node.data + " ";
node = node.next;
}
return str;
}
}
const a = new Node("To Kill a Mockingbird, ");
const b = new Node("Huckleberry Finn, ");
const c = new Node("Pride and Prejudice, ");
const d = new Node("Lord of the Flies, ");
const e = new Node("Alice in Wonderland, ");
const f = new Node("The Old Man and the Sea, ");
const g = new Node("Atlas Shrugged");
l = new LinkedList();
l.head = a;
a.next = b;
b.next = c;
c.next = d;
d.next = e;
e.next = f;
f.next = g;
console.log(l.printList());
解决方案
一个简单的解决方案是迭代和交换数据。
查看此实现: https ://www.javatpoint.com/program-to-sort-the-elements-of-the-singly-linked-list
查看 sortList() 部分。
推荐阅读
- javascript - not able to switch icon in jquery
- c - 如何根据 CMake 变量拥有一个串行和并行工作的代码
- javascript - Sum similar keys in an array of objects In javascript
- javascript - 使用 nodeJS 在用户 Web 浏览器上打开一个 url
- java - 通过 java 获取 S3 存储桶中文件上的 TAG - 密钥不存在
- azure - 更新 azure-sdk-for-go 库依赖项
- linux - How to cut string="Domain_12345_20180821230101.dat" into 12345_20180821 in Bash
- php - Woocommerce中基于嵌套IF语句中的多个数组的条件
- spring-data-jpa - 创建具有一对一关系的查询
- sql - 如何查找两个日期之间的重复值