題目鏈接: https://leetcode-cn.com/problems/middle-of-the-linked-list/
思路:用快慢指針,快指針每次走2步,慢指針每次走1步,路程相同(鏈表長度一定)的情況下,快指針的速度是慢指針的2倍,當(dāng)快指針走完鏈表的時候,慢指針在鏈表的中間點。
var middleNode = function(head) {
slow = fast = head;
while (fast && fast.next) { // 注意判斷條件,fast是會先遍歷完鏈表的,要保證fast.next不為空
slow = slow.next;
fast = fast.next.next;
}
return slow;
};