leetcode_142:Linked List Cycle
题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.
Note: Do not modify the linked list.
解法1: Fast_Slow_Ptr_Method
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
//note1: Firstly, check the head ptr.
if(!head || !head->next) return NULL;
ListNode* fast = head;
ListNode* slow = head;
ListNode* late = head;
//note2: Here need to check the two steps fast_ptr, It should be mentioned if we use fast&slow ptr to solve problem.
while((fast->next) && (fast->next->next))
{
fast = fast -> next -> next;
slow = slow -> next;
if(fast == slow)
{
while(slow!=late)
{
slow = slow -> next;
late = late -> next;
}
return slow;
}
}
return nullptr;
}
};
判断是否存在环的过程用到了快慢指针,快指针两倍于慢指针,快指针和慢指针相遇意味着一定有环存在。之后用先后指针来确定环的其实位置,类似于数学上的追及问题。当快指针和慢指针相遇时,对应的节点指针可能在环上的任一点,假设此时快指针所走的节点个数为2s, 慢指针所走节点个数为s, 两者的差s正好为环所包含节点个数的整数倍。
当快慢指针相遇的同时,启用late指针从head出发,与slow指针相同速度遍历,此时late指针与slow指针相距s个节点,两者的距离查正好是环包含节点个数的整数倍。因此,两指针必定会相遇,由于二者遍历速度相同, 并且,late和slow相遇时,对应的节点指针一定在入环的第一个点。
解法1: 利用vector来存储遍历过的位置
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(!head) return NULL;
vector<ListNode*> pos;
while(head != NULL)
{
if(find(pos.begin(), pos.end(), head)== pos.end())
{
pos.push_back(head);
head = head -> next;
}
else
{
return head;
}
}
return NULL;
}
};
在该种方法中,用到了vector容器,将元素放到vector中需要调用push_back(); 查找vector中的元素可以调用find(Vec.start(), Vec.end(), key), 该函数返回值为vector中key值对应的地址,*find(Vec.start(), Vec.end(), key)可以表示出key的值。