判斷連結串列中是否有環
阿新 • • 發佈:2020-12-29
技術標籤:牛客網
這裡可以使用使用unordered_set,避免排序;當我們迭代連結串列是,當一次查詢這個地址,發現set中有,那麼我們判斷這裡有環;
/**
* 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*> m;
while (head) {
if (m.find(head) != m.end()) return true;
m.insert(head);
head = head->next;
}
return false;
}
};