Article Directory
Problem Description
Given a node with a head
The non-empty singly linked list of returns the intermediate node of the linked list.
If there are two intermediate nodes, the second intermediate node is returned.
Problem solving report
Fast and slow pointer method Set the fast and slow pointers, the fast pointer is twice the speed of the slow pointer, when the fast pointer goes to the end, the slow pointer goes to the middle
Implementation code
class Solution {
public:
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;
}
};