148. 排序链表
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function (head) {
if (head === null) return head;
let arr = [];
while (head !== null) {
arr.push(head.val);
head = head.next;
}
let result = arr.sort((a, b) => {
return a - b;
});
let result_head = new ListNode(result[0], null);
let test = result_head;
result.forEach((data, index) => {
if (index !== 0) {
let temp = new ListNode(data, null);
test.next = temp;
test = temp;
}
});
return result_head;
};
js 初始化单链表
// 节点
class Node {
constructor(value) {
this.val = value;
this.next = null;
}
}
// 利用数组来初始化单链表
class NodeList {
constructor(arr) {
let head = new Node(arr.shift());
let next = head;
arr.forEach((data) => {
next.next = new Node(data);
next = next.next;
});
return head;
}
}
let test = new NodeList([1, 2, 3, 4]);
while (test !== null) {
console.log(test.val);
test = test.next;
}
评论区