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?

【题意】

给定一个链表,确定它是否包含一个环。

【分析】

最容易想到的方法是,用一个哈希表 unordered_map<int, bool> visited,记录每个元素是否被访问过,一旦出现某个元素被重复访问,说明存在环。

空间复杂度 O(n),时间复杂度 O(N )。

最好的方法是时间复杂度 O(n),空间复杂度 O(1) 的。设置两个指针,一个快一个慢,快的指针每次走两步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。

【代码】

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head,*fast = head;
        while(fast != NULL && fast->next != NULL){
            //慢指针走一步
            slow = slow->next;
            //快指针走两步
            fast = fast->next->next;
            if(slow == fast){
                return true;
            }
        }
        return false;
    }
};


LeetCode之Linked List Cycle

上一篇:centos 下 boost1.55 编译和安装


下一篇:蓝桥杯 【基础练习】 十六进制转十进制