ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
while (fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
自己写的不够简洁
ListNode *middleNode(ListNode *head) {
if (head == nullptr || head->next == nullptr)
return head;
ListNode *slow = head, *fast = head->next;
while (fast->next != nullptr) {
fast = fast->next;
slow = slow->next;
if (fast->next == nullptr)
return slow;
fast = fast->next;
}
return slow->next;
}