导航

LeetCode142:Linked List Cycle II

Posted on 2018-02-09 11:15  老刘想当个AI工程师  阅读(106)  评论(0)    收藏  举报

法一!!!利用set集合

环中的元素依次遍历 原集合有就返回 原集合没有就插入

/**
* 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) {
std::set<ListNode *> node_set;
while(head){
if(node_set.find(head)!=node_set.end()){
return head;
}
else{
node_set.insert(head);
head=head->next;
}
}

return NULL;
}
};

法二!!!!

利用跑得快的会把跑得慢的套圈的思想 在这个题目中 设置了两个指针 fast和slow

fast一次走两个节点 slow一次走一个

fast所走路程是slow的两倍

 

/**

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

        ListNode * fast = head;

        ListNode * slow = head;

        ListNode * meet = NULL;

        

        if(head==NULL){

            return NULL;

        }

        

        while(fast){

            fast = fast -> next;

            slow = slow -> next;

            if(!fast){

                return NULL;

            }

        

                fast = fast -> next;

                if(fast==slow){

                    meet = fast;

                    break;

                

            }

        }

        

      

        

        while(head&&meet){

            if(head==meet){

                return head;

            }

            

                head = head -> next;

                meet = meet -> next;

            

        }

       return NULL;

    }

};