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

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

判断链表中是否有环,不能用额外的空间,可以使用快慢指针,慢指针一次走一步,快指针一次走两步,若是有环则快慢指针会相遇,若是fast->next==NULL则没有环。

值得注意的是:在链表的题中,快慢指针的使用频率还是很高,值得注意。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     bool hasCycle(ListNode *head) 
12     {
13         ListNode *pFast=head;
14         ListNode *pSlow=head;
15 
16         while(pFast&&pFast->next)
17         {
18             pSlow=pSlow->next;
19             pFast=pFast->next->next;
20             if(pFast==pSlow)
21                 return true;
22         }    
23         return false;
24     }
25 };

 

相关文章:

  • 2021-11-21
  • 2022-03-04
  • 2021-06-18
  • 2021-09-11
  • 2022-12-23
  • 2021-10-01
  • 2021-10-22
  • 2021-11-09
猜你喜欢
  • 2021-04-16
  • 2022-12-23
  • 2022-12-23
  • 2021-10-17
  • 2022-12-23
  • 2022-01-12
相关资源
相似解决方案