思路1:
用 set 存储每个节点的位置,判断是否有重复的节点,重复说明有环,时间复杂度 o(n),空间复杂度 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) { unordered_set<ListNode*> st; ListNode *p = head; if(p==NULL||p->next==NULL) { return 0; } st.insert(p); while(p!=NULL) { p = p->next; unordered_set<ListNode*>::iterator it = st.find(p); if(it!=st.end()) { return 1; } else { st.insert(p); } } return 0; } };
思路2:
快慢指针,开始 快= 慢, 每次移动 快+2, 慢+1, 有环 快慢相遇,否则快先遇到NULL,时间复杂度o(n), 空间复杂度o(1)。
代码:
/** * 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) { ListNode *fast = head, *slow = head; while(fast!=NULL&&fast->next!=NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) return 1; } return 0; } };
思路1:
用 set 存储每个节点的位置,判断是否有重复的节点,重复说明有环,且重复的节点即为环的入口。时间复杂度 o(n),空间复杂度 o(n)
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { unordered_set<ListNode*> st; ListNode *p = head; if(p==NULL||p->next==NULL) { return NULL; } st.insert(p); while(p!=NULL) { p = p->next; unordered_set<ListNode*>::iterator it = st.find(p); if(it!=st.end()) { return *it; } else { st.insert(p); } } return NULL; } };
思路2:
快慢指针找到环的入口,开始 快= 慢, 每次移动 快+2, 慢+1,无环快先遇到NULL,有环快慢相遇,相遇之后, 慢= head,快+1, 慢+1, 再次快慢相遇的点为环的入口。时间复杂度o(n), 空间复杂度o(1)。
代码
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode *slow = head, *fast = head; while(fast!=NULL&&fast->next!=NULL) { fast = fast->next->next; slow = slow->next; if(fast == slow) { slow = head; while(fast!=slow) { fast= fast->next; slow = slow->next; } return fast; } } return NULL; } };
原文:https://www.cnblogs.com/jessica216/p/13376015.html