定义两个引用fast和slow,fast每次走两步,slow每次走一步,当fast走到链表尾部时,slow处于链表中间结点。
class Solution {
public ListNode middleNode(ListNode head) {
if (head==null) {
return null;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
}