leetcode 141 环形链表

简介

思路

因为C++可以存储地址, 直接判断地址是否被访问过即可.

code

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *h) {
        map<struct ListNode *, bool> m;
        bool check = false;
        while(h){
            if(m[h] == true){
                check = true;
                break;
            }else{
                m[h] = true;
            }
            h = h->next;
        }
        return check;
    }
};
public class Solution {
    public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while(head != null){
            if(!seen.add(head)){ // 如果已经存在了这个东西, add 会返回false.
                return true;
            }
            head = head.next;
        }
        return false;
    }
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14788988.html