一日一练: 重排链表

117 阅读1分钟

给定一个单链表 L 的头节点 head ,单链表 L 表示为:L0 → L1 → … → Ln - 1 → Ln 请将其重新排列后变为:L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

解题思路

如下:

image.png

代码:

function reorderList(head: ListNode | null): void {
  // 1. 快慢指针找中间节点
  let slow = head
  let fast = head
  while (fast) {
    ;(fast = fast.next) && (fast = fast.next)
    if (fast !== null) {
      slow = slow.next
    }
  }
  let next = slow.next
  slow.next = null
  // 2. 翻转
  let curr2 = reverse(next)
  let curr1 = head
  // 3. 拼接
  while (curr1) {
    const curr1Next = curr1.next
    curr1.next = curr2
    curr1 = curr1Next
    if (curr2) {
      const curr2Next = curr2.next
      curr2.next = curr1
      curr2 = curr2Next
    }
  }
}
// 翻转
function reverse(head: ListNode | null) {
  let cur = head
  let pre = null
  while (cur) {
    let next = cur.next
    cur.next = pre
    pre = cur
    cur = next
  }
  return pre
}