148. 排序链表

  • https://leetcode-cn.com/problems/sort-list/
    1. /**
    2. * Definition for singly-linked list.
    3. * function ListNode(val, next) {
    4. * this.val = (val===undefined ? 0 : val)
    5. * this.next = (next===undefined ? null : next)
    6. * }
    7. */
    8. /**
    9. * @param {ListNode} head
    10. * @return {ListNode}
    11. */
    12. var sortList = function(head) {
    13. if (head === null) return head
    14. let arr = []
    15. while (head !== null) {
    16. arr.push(head.val)
    17. head = head.next
    18. }
    19. let result = arr.sort((a, b) => {return a - b})
    20. let result_head = new ListNode(result[0], null)
    21. let test = result_head
    22. result.forEach((data, index) => {
    23. if (index !== 0) {
    24. let temp = new ListNode(data,null)
    25. test.next = temp
    26. test = temp
    27. }
    28. })
    29. return result_head
    30. };

    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 } ```