image.png
思路: 定义一个可双向出节点的队列,将链表遍历进去,这样的话,队列就是[1,2,3,4,5], 然后依次出1,5,再是2,4,最后是3,也就是先出队列的头节点和尾节点,然后连接,这里最重要的是,不要忘记5和2的连接。
/**
* 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 === null) return null;
let node = head;
let queue = []; // 定义一个可以双向出节点的队列
while(node){ // 将链表中元素加入队列中
queue.push(node);
node = node.next;
}
while(queue.length > 0){
let shift_node = queue.shift(); // 头部节点
let pop_node = queue.pop(); // 尾部节点
if(pop_node){ // 如果链表节点为奇数个数,则最后一个无pop节点
shift_node.next = pop_node; // 头节点的下一个节点指向尾节点
pop_node.next = queue.length ? queue[0] : null; // 交换节点后,让队列中开始的尾节点指向原有链表的下一个节点,这步很重要
} else {
shift_node.next = null;
}
}
return head;
};











网友评论