Problem Description

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

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

 

Problem Solution

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

 

 

 

 

相关文章:

  • 2022-01-31
  • 2021-08-08
  • 2021-11-14
  • 2021-10-23
  • 2021-11-13
  • 2021-06-09
  • 2021-07-16
  • 2021-11-22
猜你喜欢
  • 2021-09-27
  • 2021-05-27
  • 2021-12-28
  • 2021-07-12
  • 2021-07-26
  • 2021-08-02
  • 2021-06-07
相关资源
相似解决方案