1. 程式人生 > >leetcode 141/142環形連結串列

leetcode 141/142環形連結串列

/**
 * 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) {
//        if(head==NULL || head->next==NULL)
//            return false;
        ListNode *p1=head;
        ListNode *p2=head;
        while(p2 && p2->next){
            p1=p1->next;
            p2=p2->next->next;
            if(p1==p2)
                return true;
        }
        return false;
    }
};

返回環的起點:

/**
 * 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 *p1,*p2;
        p1=head;
        p2=head;
        while(p2 && p2->next){
            p1=p1->next;
            p2=p2->next->next;
            if(p1==p2){
                // p1 points back to head,p2 still stand where they have met
                // p1,p2 take the same steps
                // when they meet again, that's where the cycle starts
                p1=head;
                while(p1!=p2){
                    p1=p1->next;
                    p2=p2->next;
                }
                return p1;
            }
        }
        return NULL;
    }
};