[路飞]_LeetCode题143重排链表

373 阅读1分钟

题目描述

给定一个单链表 L 的头节点 head ,单链表 L 表示为:

L0 → L1 → … → Ln - 1 → Ln 请将其重新排列后变为:

L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → … 不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

 

示例 1:

image.png

输入:head = [1,2,3,4] 输出:[1,4,2,3] 示例 2:

image.png

输入:head = [1,2,3,4,5] 输出:[1,5,2,4,3]  

提示:

链表的长度范围为 [1, 5 * 10410^4] 1 <= node.val <= 1000

来源:力扣(LeetCode) 链接:leetcode-cn.com/problems/re… 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

题解思路

  1. 将链表拆分成单个节点按原顺序村放到数组中。
  2. 拿一个头节点出来。
  3. 拿一个尾结点出来。
  4. 头结点指向尾结点。
  5. 尾结点指向头结点的下一个节点。
  6. 重复前面步骤,直到找到连接的终点。

image.png

题解代码

 * @lc app=leetcode.cn id=143 lang=javascript
 *
 * [143] 重排链表
 */

// @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 {void} Do not return anything, modify head in-place instead.
 */
var reorderList = function(head) {
  //一个节点或双节点链表直接原样返回
  if(!head.next || !head.next.next) return head;
  
  let nodes = [],cur = head;
  //按顺序将链表拆分成单个独立节点
  while (cur) {
    let next = cur.next;
    cur.next = null;
    nodes.push(cur);
    cur = next;
  }
  //定义首尾指针,相向移动
  let left = 0, right = nodes.length - 1;
  while (left < right) {
    nodes[left].next = nodes[right];
    //防止偶数个数节点链表中间两个点连接成环
    if (left + 1 < right) {
      nodes[right].next = nodes[left + 1];
    }
    left++;
    right--;
  }
  return nodes[0];
};
// @lc code=end