首页 > 代码库 > [LeetCode] Linked List Cycle 单链表中的环

[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?

 

开始以为这道题只需要注意不使用额外空间即可,于是写了个时间复杂度为O(n^2)暴力搜索算法,如下:

 

/** * Dumped, Time Limit Exceeded */class Solution {public:    bool hasCycle(ListNode *head) {        if (!head || !head->next) return false;        ListNode *pre = head;        ListNode *cur = head->next;        while (cur) {            pre = head;            while (cur->next != pre && pre != cur) {                pre = pre->next;            }            if (cur->next == pre && pre != cur) return true;            cur = cur->next;        }        return false;    }};

 

可是OJ还是不给通过,原因是Time Limit Exceeded,还是需要把时间复杂度缩小的O(n)才行,于是上网搜各位大神的方法,发现果然很神奇。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。实在是太巧妙了,要是我肯定想不出来。代码如下:

 

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        if (!head || !head->next) return false;        ListNode *slow = head;        ListNode *fast = head;        while (slow && fast) {              slow = slow->next;            fast = fast->next;            if (!fast) return false;            fast = fast->next;            if (slow == fast) return true;        }        return false;    }};

 

[LeetCode] Linked List Cycle 单链表中的环