题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ #include<unordered_map> class Solution { public: bool hasCycle(ListNode *head) { ListNode* CountPoint = head; //定义一个哈希表 unordered_map<ListNode*,int>mymap; if(head->next ==nullptr){return false;} if(head==nullptr){return false;} CountPoint = CountPoint->next; //判断mymap是否出现重复元素,先走一遍链表,结束条件为出现重复元素或者最后一个元素指向Null while(mymap[CountPoint]<1 && CountPoint->next !=nullptr){ mymap[CountPoint]++; CountPoint = CountPoint->next; } if (CountPoint->next==nullptr) {return false; } else { return true; } } };