题解 | #判断链表中是否有环#

判断链表中是否有环

https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9

## 链表遍历 +  set判重
* 对链表进行遍历,通过数组来记录,该节点是否出现,如果出现,则这个节点就是链表的环形的入口


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    unordered_set<ListNode*> st;
    bool hasCycle(ListNode *head) {
        if(head == NULL) return 0;
        while(head){
            if(st.count(head)) return 1;
            st.insert(head);
            head=head->next;
        }
        return 0;
    }
};

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务