Lituo 876. The middle node of the linked list

topic

Give you the head node of the singly linked list, head,please find and return the middle node of the linked list. If there are two intermediate nodes, return the second intermediate node.

answer

Set the speed pointers slow and fast. Slow takes one step at a time, and fast takes two steps at a time. When fast is finished, slow just points to the middle node of the linked list. As can be seen from the figure below, when the number of linked list nodes is odd, fast points to the end node of the linked list, and slow just points to the middle node; when the number of linked list nodes is even, fast points to NULL, and slow just points to the second node. an intermediate node. So the condition of the loop is while (fast && fast->next), and finally return to slow.

 code show as below:

struct ListNode* middleNode(struct ListNode* head)
{
    struct ListNode* slow = head;
    struct ListNode* fast = head;
    while (fast && fast->next)
    {
        slow = slow->next;
        fast = fast->next->next;
    }
    return slow;
}

Guess you like

Origin blog.csdn.net/minLi_/article/details/131665321