题目描述
给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例 1:
给定链表 1->2->3->4, 重新排列为 1->4->2->3.
示例 2:
给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
解题思路
方法一:使用双指针和 存储
- 先使用数据存储链表的每一个节点
- 然后使用双指针重新建立链表之间的关系
代码
/**
* 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) {
return head;
}
let node = [];
let pos = head;
let tmp = null;
while (pos) {
tmp = pos.next;
pos.next = null;
node.push(pos);
pos = tmp;
}
let i = 0,
j = node.length - 1;
while (i < j) {
node[i].next = node[j];
i++;
if (i === j) {
break;
}
node[j].next = node[i];
j--;
}
return node[0];
};