重新排序链表而不创建新的链表



社区!我的问题是,我必须以这样一种方式对链表进行排序,即不创建新的链表,而是返回相同的链表。例如,如果我有:头部-->[8] -->[15] -->[1] 我应该返回Head->[1] -->[8] -->[15]我现在的代码,可能我的代码很糟糕而且不正确,但我是新手,找不到答案。谢谢你抽出时间!

LinkedList.prototype.orderList = function() {
//temporary node to swap the element
let current = this.head;
if (LinkedList.value === null) return "Empty";
if (LinkedList.next.value === null) return "Orderer list"
while (this.head.next.value !== null) {
for (let i; i < LinkedList.length; i++)
if (LinkedList.head.value > LinkedList.head.next.value) {
current = LinkedList.head;
} else if (linkedList.LinkedList.head.next.value)
current = linkedList.head;
}
};

我做了经典的简单排序(或冒泡排序)。其中in - 1ji + 1n。它奏效了。

function Node(value) {
this.value = value || null;
this.next = null;
}
function print(list) {
var head = list;
var arr = [];
while (head) {
arr.push(head.value);
head = head.next;
}
console.log("" + arr)
}
var list = new Node(3);
list.next = new Node(9);
list.next.next = new Node(6);
list.next.next.next = new Node(2);
function sort(list) {
if (!list || !list.next) {
return;
}
for (var i = list; i.next != null; i = i.next) {
for (var j = i.next; j != null; j = j.next) {
if (i.value > j.value) {
var temp = i.value
i.value = j.value
j.value = temp;
}
}
}
}
print(list)
sort(list)
print(list)

最新更新