快手面试真题-判断链表是否有环,求入环位置

【快手】2019提前批校招面试题

题目地址:

判断链表是否有环:https://leetcode.com/problems/linked-list-cycle/

求入环的位置:https://leetcode.com/problems/linked-list-cycle-ii/

 

解题思路:

快手面试真题-判断链表是否有环,求入环位置_第1张图片

 

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;
        }
    }
};

 

你可能感兴趣的:(秋招笔试面试刷题)