148. 排序链表
- https://leetcode-cn.com/problems/sort-list/
/*** 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 headlet 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_headresult.forEach((data, index) => {if (index !== 0) {let temp = new ListNode(data,null)test.next = temptest = temp}})return result_head};
js初始化单链表
```javascript // 节点 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 } ```
