寻找单链表中间元素

Leetcode May 28, 2020
Node* findMiddle(Node* list) {
    int fast_idx = 0;
    int slow_idx = 0;
    Node* fast = list->next;
    Node* slow = fast;

    while(fast) {
        if (fast_idx / 2 > slow_idx) {
            slow_idx++;
            slow = slow->next;
        }
        fast_idx++;
        fast = fast->next;
    }
    return slow;
}

快慢指针,当fast快过slow两倍当时候,把slow指针补上

时间复杂度O(1)

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.