42 lines
1.0 KiB
JavaScript
42 lines
1.0 KiB
JavaScript
/**
|
|
* 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) {
|
|
const node = head
|
|
let lastNode = getLastNode(node)
|
|
let currentNode = node
|
|
while (!(currentNode === lastNode || currentNode.next === lastNode)) {
|
|
const secNode = currentNode.next
|
|
const lastPrevNode = getPrevNode(node, lastNode)
|
|
currentNode.next = lastNode
|
|
lastNode.next = secNode
|
|
currentNode = secNode
|
|
lastNode = lastPrevNode
|
|
lastNode.next = null
|
|
}
|
|
return head
|
|
};
|
|
|
|
function getLastNode(node) {
|
|
let lastNode = node;
|
|
while (lastNode.next) {
|
|
lastNode = lastNode.next
|
|
}
|
|
return lastNode
|
|
}
|
|
|
|
function getPrevNode(head, node) {
|
|
let currentNode = head;
|
|
while (currentNode && currentNode.next !== node) {
|
|
currentNode = currentNode.next
|
|
}
|
|
return currentNode
|
|
} |