单链表1->2->3->4->5 变成1->5->2->4->3
//链表类似于下边这样
const head = {
val: 1,
next: {
val: 2,
next: {
val: 3,
next: {
val: 4,
next: null
}
}
}
}
const reverse = (head) =>{
if(!head || !head.next) return head;
if(!head.next.next){
const temp = head.next;
head.next.next = head;
head.next = null
return temp;
}
const temp = reverse(head.next);
head.next.next = head;
head.next = null
return temp;
}
var reorderList = function(head) {
let current = head
let arr = []
while(current){
if(current.next){
current.next = reverse(current.next)
}
if(current){
current = current.next
}
}
return current
};
网友评论