【题目】
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) 的。设置两个指针,一个快一个慢,快的指针每次走两步,慢的指针每次走一步,如果快指针和慢指针相遇,则说明有环。
【代码】
/*---------------------------------------------------------
* 日期:2015-04-23
* 作者:SJF0115
* 题目: 141.Linked List Cycle
* 网址:https://leetcode.com/problems/linked-list-cycle/
* 结果:AC
* 来源:LeetCode
* 博客:
------------------------------------------------------------*/
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
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;
}
};