题目:Given the head of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
返回链表的中间的节点,如果是二个中间节点,返回第二个
方法一:
第一篇 遍历 链表总长度 (链表与数组不同,链表要遍历才得的了长度)
第二次遍历 中间节点
方法二:
使用快慢指针
快指针走二步
慢指针走一步
所以当快指针走到最后一步时,慢指针刚好到链表中间
var middleNode = function(head) {
let fast=head;
while(fast && fast.next){
//这个循环退出时,就意味着fast快指针走到了尽头
fast=fast.next.next;
head=head.next;
}
return head;
};