LeetCode:142. 環形鏈表 II

/**
 * 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) {
        set<ListNode *>obj;///爲了防止元素內容相同,這裏選擇存儲整個鏈表的節點
        while(head)
        {
            if(obj.count(head)==1)
            {
                return head;
            }
            obj.insert(head);
            head=head->next;
        }
        return NULL; 
    }
};
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章