📅  最后修改于: 2023-12-03 15:28:26.528000             🧑  作者: Mango
在Javascript中,我们可以通过更改链接对链表进行排序。下面是一个描述如何对0、1和2进行排序的Javascript程序。
本程序通过创建三个指针,分别指向值为0、1和2的节点。使用一个循环,遍历链表中的每一个值,并将其连接到指定节点的链表上。最后,将所有链表连接起来形成完整的有序链表。
function sortLinkedList(head) {
let zeroNode = new ListNode(-1);
let oneNode = new ListNode(-1);
let twoNode = new ListNode(-1);
let zeroPointer = zeroNode;
let onePointer = oneNode;
let twoPointer = twoNode;
let current = head;
while (current) {
if (current.val === 0) {
zeroPointer.next = current;
zeroPointer = zeroPointer.next;
} else if (current.val === 1) {
onePointer.next = current;
onePointer = onePointer.next;
} else {
twoPointer.next = current;
twoPointer = twoPointer.next;
}
current = current.next;
}
zeroPointer.next = oneNode.next || twoNode.next;
onePointer.next = twoNode.next;
twoPointer.next = null;
return zeroNode.next;
}
-1
的值。这是为了避免在后续将节点连接到它们时出现null
或者undefined
的情况。zeroPointer
指向值为0的节点,onePointer
指向值为1的节点,twoPointer
指向值为2的节点。current
来表示当前遍历的节点,从头节点开始遍历每个节点。0
,则将它连接到zeroNode
的链表上,如果是1
,则将它连接到oneNode
的链表上,如果是2
,则将它连接到twoNode
的链表上。zeroNode
和oneNode
需要比较它们的下一个节点是否都存在,如果都存在,则将它们叠加在一起。最后,将twoNode
的链表连接到最后一个节点上,并将最后一个节点的next
置为null
。zeroNode.next
作为排序后的链表的头节点。上文中的完整代码:
function sortLinkedList(head) {
let zeroNode = new ListNode(-1);
let oneNode = new ListNode(-1);
let twoNode = new ListNode(-1);
let zeroPointer = zeroNode;
let onePointer = oneNode;
let twoPointer = twoNode;
let current = head;
while (current) {
if (current.val === 0) {
zeroPointer.next = current;
zeroPointer = zeroPointer.next;
} else if (current.val === 1) {
onePointer.next = current;
onePointer = onePointer.next;
} else {
twoPointer.next = current;
twoPointer = twoPointer.next;
}
current = current.next;
}
zeroPointer.next = oneNode.next || twoNode.next;
onePointer.next = twoNode.next;
twoPointer.next = null;
return zeroNode.next;
}
0
、1
和2
的节点的链表。