单向链表找中点,快慢指针:

  • slow一次走一步,fast一次走两步

  • fast走到头的时候,slow正好走了一半,也就是中点位置。

c++实现

class Solution {
public:
    ListNode* middleNode(ListNode* head) {
        // write code here
        ListNode* slow=head, *fast=head;
        while(fast && fast->next){
            slow = slow->next;
            fast = fast->next->next;
        }
        return slow;
    }
};

python实现

class Solution:
    def middleNode(self , head: ListNode) -> ListNode:
        fast = head
        slow = head
        while  fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        return slow