Leetcode141

判断是否有环

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

Leetcode142

如果有环,请返回环的开始位置

/** * 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 = head,*p2 = head;
        while(p2 !=0 && p2->next != 0){
            p1 = p1->next;
            p2 = p2->next->next;
            if(p1 == p2){
                break;
            }
        }
        if(p2==0||p2->next==0) return 0;
        for(p1=head;p1!=p2;p1=p1->next,p2=p2->next);
        return p2;
    }
};