重排链表
This commit is contained in:
42
1.重排链表/解1.js
Normal file
42
1.重排链表/解1.js
Normal file
@ -0,0 +1,42 @@
|
||||
/**
|
||||
* 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
|
||||
}
|
Reference in New Issue
Block a user