141、 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?
思路
非常简单的一道题,如果链表有环,则在遍历的时候永远不会结束,一直在环内转圈。
所以,设置快慢指针,如果相遇,则说明有环。
代码(C++)
/**
* 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 (NULL == head || NULL == head->next)
return false;
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
142、Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
思路
在上一题的基础上,slow和fast相遇后,slow和head同时出发,每次一个步长,相遇的时候就是交点。
代码(C++)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head)
{
if (NULL == head || NULL == head->next)
return false;
ListNode* slow = head;
ListNode* fast = head;
while (fast->next && fast->next->next)
{
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
{
ListNode* tmp = head;
while (tmp != slow)
{
tmp = tmp->next;
slow = slow->next;
}
return tmp;
}
}
return NULL;
}
};