My Submissions
Question
Total Accepted: 88665 Total
Submissions: 241622 Difficulty: Medium
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Subscribe to see which companies asked this question
Hide Tags
Linked List Two
Pointers
Hide Similar Problems
(M) Linked List Cycle II
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
//思路首先:如果有環?遍歷鏈表將無法走完,如果無環終會走到尾為NULL的位置
//讓一個指針每次走一個,一個指針每次走兩個位置,如果其中一個為NULL則無環,如果相遇了
//則有環
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL)
return false;
ListNode *showNode=head;
ListNode *fastNode=head;
while(true)
{
if(showNode->next!=NULL)
showNode=showNode->next;
else
return false;
if(fastNode->next!=NULL && fastNode->next->next!=NULL)
fastNode=fastNode->next->next;
else
return false;
if(showNode==fastNode)
return true;
}
return false;
}
};