您的位置:首页 > 其它

LeetCode(141)(142) Linked List Cycle I II

2015-08-09 16:43 609 查看
Linked List Cycle 代码

[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 *head) {

        set<ListNode *> visited;
        ListNode *p1;

        p1 = head;
        while(p1 != NULL) {

            if(visited.count(p1))

                return true;

            else

                visited.insert(p1);

            p1 = p1->next;

        }

        return false;

    }
};


Linked List Cycle II 代码

[code]/**
 * 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 *> visited;
        ListNode *p1;

        p1 = head;
        while(p1 != NULL) {

            if(visited.count(p1)) 

                return p1;

            else 

                visited.insert(p1);

            p1 = p1->next;

        }

        return NULL;

    }
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: