将给定的单链表L: L_0→L_1→…→L_{n-1}→L_n
重新排序为:L_0→L_n →L_1→L_{n-1}→L_2→L_{n-2}→…...
要求使用原地算法,不能改变节点内部的值,需要对实际的节点进行交换。
例如:
对于给定的单链表{10,20,30,40},将其重新排序为{10,40,20,30}.
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return void
*/
function reorderList( head ) {
// write code here
if(head==null||head.next==null||head.next.next==null){return head}
var arr = []
var current = head
while(current){
arr.push(current)
current = current.next
}
var i = 0
var j = arr.length-1
while(i<j){
if(i+1 == j){
break;
}
arr[i].next = arr[j]
arr[j-1].next = null
arr[j].next = arr[i+1]
i++
j--
}
return arr[0]
}
module.exports = {
reorderList : reorderList
};