From 270e53db52d21d4ba5dcec225a899dc5f1b23e12 Mon Sep 17 00:00:00 2001 From: Wen <409053122@qq.com> Date: Mon, 14 Aug 2023 14:14:30 +0800 Subject: [PATCH] =?UTF-8?q?[148]=20=E6=8E=92=E5=BA=8F=E9=93=BE=E8=A1=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/leecode/javascript/148.排序链表.js | 48 ++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 src/leecode/javascript/148.排序链表.js diff --git a/src/leecode/javascript/148.排序链表.js b/src/leecode/javascript/148.排序链表.js new file mode 100644 index 0000000..c766f95 --- /dev/null +++ b/src/leecode/javascript/148.排序链表.js @@ -0,0 +1,48 @@ +/* + * @lc app=leetcode.cn id=148 lang=javascript + * + * [148] 排序链表 + */ + +// @lc code=start +/** + * 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 || !head.next) { + return head; + } + let slow = head, + fast = head.next; + while (fast && fast.next) { + slow = slow.next; + fast = fast.next.next; + } + const tmp = slow.next; + slow.next = null; + let left = sortList(head); + let right = sortList(tmp); + let h = new ListNode(0); + const ret = h; + while (left && right) { + if (left.val < right.val) { + h.next = left; + left = left.next; + } else { + h.next = right; + right = right.next; + } + h = h.next; + } + h.next = left == null ? right : left; + return ret.next; +}; +// @lc code=end