Linked List Cycle

来源:互联网 发布:instagram拍照软件好吗 编辑:程序博客网 时间:2024/06/03 23:14

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */ #include<set>class Solution {public:    bool hasCycle(ListNode *head) {        set<ListNode*> listSet;        listSet.insert(head);        ListNode* p = head;        while(p&&p->next)        {            if(listSet.find(p->next)==listSet.end()){                listSet.insert(p->next);                p=p->next;            }else{                return true;            }        }        return false;    }};
class Solution {public:    bool hasCycle(ListNode *head) {        ListNode *slow = head,*fast = head;        while(fast&&fast->next)        {            slow = slow->next;            fast = fast->next->next;            if(slow==fast) return true;        }        return false;    }};



0 0
原创粉丝点击