[leetcode - Bliend-75 ] 143. Reorder List (Medium)

You are given the head of a singly linked-list. The list can be represented as:

L0 → L1 → … → Ln - 1 → Ln
Reorder the list to be on the following form:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
You may not modify the values in the list's nodes. Only nodes themselves may be changed.

Example

Input: 1 -> 2 -> 3 -> 4
Output: 1 -> 4 -> 2 -> 3

Input: 1 -> 2 -> 3 -> 4 -> 5
Output: 1 -> 5 -> 2 -> 4 -> 3

Step

先建立快慢指针找到 linked list 的中间点
  // find the middle  let fast = head;  let slow = head;  while (fast.next?.next) {    slow = slow.next;    fast = fast.next.next;  }

http://img2.58codes.com/2024/T1RCCO0.gif

将 linked list 由刚刚找的的中间 node 分为两个 linked list 并将右边的 linked list 反转
http://img2.58codes.com/2024/gfnn539.gif

将左边的 linked list 和右边的 linked list 合併
http://img2.58codes.com/2024/I9ZMWQe.gif

Coding

/** * @param {ListNode} head * @return {void} Do not return anything, modify head in-place instead.*/var reorderList = function (head) {  // find the middle  let fast = head;  let slow = head;  while (fast.next?.next) {    slow = slow.next;    fast = fast.next.next;  }  // reverse  let curr = slow.next;  slow.next = null;  let prev = null;  while (curr) {    let tmp = curr.next;    curr.next = prev;    prev = curr;    curr = tmp;  }  let h1 = head;  let h2 = prev;  while (h2) {    let tmp = h1.next;     h1.next = h2;    h1 = h2;    h2 = tmp;  }};

Time complexity: O(n)


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章