Leetcode 876. Intermediate node of linked list

Problem Description

Given a node with a head h e a d 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;
    }
};
MD_
Published 139 original articles · praised 8 · 10,000+ views

Guess you like

Origin blog.csdn.net/qq_27690765/article/details/105040711