Linked List Cycle

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

Follow up:
Can you solve it without using extra space?

思路:1.两个指针,一个走1步,一个走2步,如果相遇则有环

注意: 在使用p->next时,一定要判断p是否为空。使用p->next->next时,检查p->next是否为空

2.还有一种方法是用递归哈哈哈。检查

/**
 * 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;
        ListNode *p2 = head;
        while(p1 && p2 && p2->next){
            p1=p1->next;
            p2=p2->next->next;
            if(p1==p2) return true;
        }
        return false;
    }
};
原文地址:https://www.cnblogs.com/renrenbinbin/p/4340229.html