0

所以我在解决 leetcode 的问题,我们必须返回尾部连接的节点,但是当我取时解决方案出错了fast = head->next,当我取fast = head. 我明白后者是如何正确的,但我不太明白为什么?

示例: 输入:head = [3,2,0,-4], pos = 1 输出:tail 连接到节点索引 1

错误代码

ListNode *slow = head, *fast = head->next;
    
    while(fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        
        if(slow == fast)
            break;
    }
    if(fast == NULL || fast->next == NULL){
        return NULL;
    }
    slow = head;
    while(fast != slow){
        slow = slow->next;
        fast = fast->next;
    }
    return fast;

正确的代码

ListNode *slow = head, *fast = head;
    
    while(fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        
        if(slow == fast)
            break;
    }
    if(fast == NULL || fast->next == NULL){
        return NULL;
    }
    slow = head;
    while(fast != slow){
        slow = slow->next;
        fast = fast->next;
    }
    return fast;
4

0 回答 0