题目描述:
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?
思路:
双指针遍历链表,oneNode每次向前走一步,twoNode每次向前走两步。若两个指针相遇,就有环,不相遇,则无环。
处理特殊情况,若头指针为空,则无环。
代码:
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *oneNode = head;
ListNode *twoNode = head;
if(head == NULL)
return false;
while(twoNode->next != NULL && twoNode->next->next != NULL)
{
oneNode = oneNode->next;
twoNode = twoNode->next->next;
if(oneNode == twoNode)
return true;
}
return false;
}
};