一、题目
二、实现
方法一:使用数组
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return void
*/
function reorderList( head ) {
// if(!head || !head.next){return;}
let arr = [];
let p = head;
while(p){
let temp = p.next;
arr.push(p);
p.next = null; //释放内存
p = temp;
}
let i=0,j=arr.length-1;
while(i<j){ //1->2->3
arr[i].next = arr[j];//1->3
i++;
if(i==j) break;
arr[j].next = arr[i]; //1->3->2
j--;
}
}
module.exports = {
reorderList : reorderList
};
方法二:为链表节点添加pre指针
/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类
* @return void
*/
function reorderList( head ) {
if(!head || !head.next){
return head;
}
let a = head;
//1. 添加pre指针
while(a && a.next){
a.next.pre = a;
a = a.next;
}
//2. 重排列表
let b = head; //此时a指向最后的节点
while(a!==b && a.pre!==b){ //1->2->3
let temp = b.next; //即2 b=1
b.next = a; // 1->3
a = a.pre; // a = 2
b.next.next = temp; // 1->3->2
b = temp; // b=2
}
a.next = null //不写内存会超限
return head;
}
module.exports = {
reorderList : reorderList
};