[Leetcode] 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?

判断链表中是否有环,不能用额外的空间,可以使用快慢指针,慢指针一次走一步,快指针一次走两步,若是有环则快慢指针会相遇,若是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 };

 

posted @ 2017-06-15 15:39  王大咩的图书馆  阅读(216)  评论(0编辑  收藏  举报