【快手】2019提前批校招面试题
题目地址:
判断链表是否有环:https://leetcode.com/problems/linked-list-cycle/
求入环的位置:https://leetcode.com/problems/linked-list-cycle-ii/
解题思路:
AC代码:
判断链表有环
/**
* 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) {
ListNode *fast, *slow;
if(!head || !head->next){
return false;
}
fast = slow = head;
while(1){
if(!slow || !fast || !fast->next){
return false;
}
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
return true;
}
}
}
};
求入环位置
/**
* 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) {
ListNode *fast, *slow;
if(!head || !head->next){
return NULL;
}
fast = slow = head;
// 找相遇的位置
while(1){
if(!slow || !fast || !fast->next){
return NULL;
}
slow = slow->next;
fast = fast->next->next;
if(fast == slow){
break;
}
}
// 找入环的位置
fast = head;
while(1){
if(fast == slow){
return fast;
}
fast = fast->next;
slow = slow->next;
}
}
};