快指针每次走两步,慢的每次走一步,当快指针为nullptr或者下一个节点为nullptr时,就返回慢的:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode *faster = head;
ListNode *lower = head;
while(faster!=nullptr&&faster->next!=nullptr){
faster = faster->next->next;
lower = lower->next;
}
return lower;
}
};