LeetCode 141: 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?

思路:

此题目要求为判断一个链表是否有环,这应该说是一个经典的面试题目。只需要两个指针,一个走的快,一个走的慢,看慢的能不能追上快的,如果追上了那么就是有环的,否则走到链表的结尾那么就是没有环。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(!head) return false;
        ListNode *p = head;
        ListNode *q = head->next;
        while(p!=q&&p!=NULL&&q!=NULL){
            p = p->next;
            q = q->next;
            if(q!=NULL) q = q->next;
            else return false;
        }
        if(p==q) return true;
        return false;
    }
};

  

原文地址:https://www.cnblogs.com/xiamaogeng/p/4399158.html