[LeetCode]92. 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?
Subscribe to see which companies asked this question
解法1:使用两个指针p1, p2。p1从表头开始一步一步往前走,遇到null则说明没有环,返回false;p1每走一步,p2从头开始走,如果遇到p2==p1.next,则说明有环true,如果遇到p2==p1,则说明暂时没有环,继续循环。但是这个时间复杂度O(n^2),会超时Time Limit Exceeded
/** * 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 == NULL || head->next == NULL) return false; ListNode* p1 = head; while (p1 != NULL) { if (p1->next == p1) return true; ListNode* p2 = head; while (p2 != p1) { if (p2 == p1->next) return true; p2 = p2->next; } p1 = p1->next; } return false; } };
解法2:使用快慢指针,慢指针每次前移一个节点,快指针每次前移两个节点,如果后面两个指针相交,就说明存在环。时间复杂度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 == NULL || head->next == NULL) return false; ListNode *slow = head, *fast = head; while (fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; } };