一块一慢的找中间node, 快的到头,慢的就找到了. 试一下1,2,3个节点,答案就出来了:
/**
* 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) {
if(head == nullptr) {return nullptr;}
ListNode* single = head;
ListNode* jump = head;
while(jump->next) {
single = single->next;
jump = jump->next;
if(jump->next) {
jump = jump->next;
}
}
return single;
}
};