首页 > 代码库 > Linked List Cycle

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?

题目的意思是判断链表中有没有环


思路:

定义两个指针,一个慢指针,一个快指针,慢指针一次走两步,快指针一次走一步,如果有环,那么慢、快指针一定会在环中相遇

代码如下:

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


Linked List Cycle