Skip to content

重排链表 #116

Open
Open
@louzhedong

Description

习题

出处 LeetCode 算法第143题

给定一个单链表 LL0→L1→…→L**n-1→Ln ,
将其重新排列后变为: L0→L**nL1→L**n-1→L2→L**n-2→…

你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

示例 1:

给定链表 1->2->3->4, 重新排列为 1->4->2->3.

示例 2:

给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.

思路

首先定义一个数组保存所有的节点,然后从开头以及结尾依次遍历节点将所有节点连接起来

解答

/**
 * @param {ListNode} head
 * @return {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function (head) {
  if (!head) return;
  var array = [];
  while (head) {
    array.push(head);
    head = head.next;
  }
  var length = array.length;
  head = array[0];
  for (var i = 1, j = length - 1; i <= j; i++ , j--) {
    head.next = array[j];
    head = head.next;
    head.next = array[i];
    head = head.next;
  }
  head.next = null;
};

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions