单向链表找中点,快慢指针:
-
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