LeetCode 之 linked-list-cycle【检测链表中是否有环】

题目: Given a linked list, determine if it has a cycle in it.

  Follow up:
  Can you solve it without using extra space?

  思路一:要达到的目的,检测链表中是否有环,首先第一个思路可以是遍历整个链表,并标记访问过的节点,如果重复访问了某个节点,说明该链表中有环。该思路实现简单,借用一个模板map,键记录节点,值对应是否访问,为bool类型即可。但是该方法会引入 O ( N ) O(N) 的额外空间。

class Solution {
public:
    bool hasCycle(ListNode *head) {
       unordered_map<ListNode*,bool> visited;
        while(head){
        	//如果不等于最后一个值,说明之前访问过,也就是有环
            if(visited.find(head)!=visited.end())  return true;
            //访问过的节点标记为true
            visited[head] = true;
            head = head->next;
        }
        return false;
    }
};

  思路二:Follow up中提到,如果不使用额外空间应该怎么实现,参考答案中提到,可以利用两个指针,即快慢指针,如果有环,快慢指针的访问就会称为一个追及问题,快指针每次都会比慢指针快一点,总会有一个时刻会追上,那么会不会超过去,这就涉及到快指针比慢指针快多少了,如果快一个节点,那么无论环长多少,都是追及单位的倍数。

public:
    bool hasCycle(ListNode *head) {
        //if(head == nullptr) return false;认为不需要,因为fast=head,while检测fast是否为空,空指针就跳出返回false
        ListNode *slow=head;
        ListNode *fast=head;
        while(fast != nullptr && fast->next != nullptr)
        {
            fast = fast->next->next;
            slow = slow->next;
            if(fast == slow) return true;
        }
        return false;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_35479108/article/details/88257652