leetcode-华为专题-141. 环形链表_程序

 

/**
 * 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;
        // 双指针,一个指针走一步,一个指针走两步,如果有环,肯定相遇,否则返回false无环
        ListNode* p = head;
        ListNode* q = head->next->next;
        while(p&&q&&q->next){
            if(p==q)
                return true;
            p = p->next;
            q = q->next->next;
        } 
        return false;
    }
};