首页 > 解决方案 > 如何在 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());

标签: javascriptlinked-list

解决方案


一个简单的解决方案是迭代和交换数据。

查看此实现: https ://www.javatpoint.com/program-to-sort-the-elements-of-the-singly-linked-list

查看 sortList() 部分。


推荐阅读