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

来源:互联网 发布:网页页面设计软件 编辑:程序博客网 时间:2024/04/20 23:14

Linked List Cycle 代码

/** * 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 代码

/** * 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;    }};
0 0
原创粉丝点击