function ListNode(val, next) {
this.val = (val === undefined ? 0 : val)
this.next = (next === undefined ? null : next)
}
var reorderList = function (head) {
let arr = []
let cur = head
while (cur) {
arr.push(cur)
cur = cur.next
}
let len = arr.length
let half = Math.floor(len / 2)
for (let i = 0; i < half; i++) {
console.log(arr[i])
arr[i].next = arr[len - 1 - i]
arr[len - 1 - i].next = arr[i + 1]
}
arr[half].next = null
return head
};
var reorderList = function (head) {
if (!head || !head.next) {
return head
}
let middle = getMiddleNode(head)
let [left, right] = divideLeftAndRight(head, middle)
let reversedRight = reverseNodes(right)
head = merge(left, reversedRight)
return head
}
function getMiddleNode(head) {
let slow = head
let fast = head
while (slow && fast && fast.next) {
slow = slow.next
fast = fast.next.next
}
return slow
}
function divideLeftAndRight(head, middle) {
let cur = head
while (cur.next !== middle) {
cur = cur.next
}
cur.next = null
let left = head
let right = middle
return [left, right]
}
function reverseNodes(head) {
let pre = null
let cur = head
while (cur) {
let next = cur.next
cur.next = pre
pre = cur
cur = next
}
return pre
}
function merge(head1, head2) {
let l1 = head1
let l2 = head2
while (l1) {
let l1Next = l1.next
let l2Next = l2.next
l1.next = l2
if (l1Next) {
l2.next = l1Next
}
l1 = l1Next
l2 = l2Next
}
return head1
}
function print(head) {
let res = []
let cur = head
while (cur) {
res.push(cur.val)
cur = cur.next
}
console.log(res)
}
const head = new ListNode(1)
const n1 = new ListNode(2)
const n2 = new ListNode(3)
const n3 = new ListNode(4)
const n4 = new ListNode(5)
head.next = n1
n1.next = n2
n2.next = n3
n3.next = n4
print(head)
const newHead = reorderList(head)
print(newHead)