LeetCode 141. Linked List Cycle

2020-04-29  本文已影响0人  洛丽塔的云裳

0.前言

Given a linked list, determine if it has a cycle in it.
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.

Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true

Explanation: There is a cycle in the linked list, where tail connects to the second node.

Example 2:
Input: head = [1,2], pos = 0
Output: true

Explanation: There is a cycle in the linked list, where tail connects to the first node.

Example 3:
Input: head = [1], pos = -1
Output: false

Explanation: There is no cycle in the linked list.

1.c++版本

这道题其实很难,很难想到,是快慢指针的经典应用。只需要设两个指针,一个每次走一步的慢指针和一个每次走两步的快指针,如果链表里有环的话,两个指针最终肯定会相遇。

class Solution {
public:
    bool hasCycle(ListNode *head) {
        if (!head || !head->next)
            return false;
        ListNode *fast = head -> next -> next;
        ListNode *slow = head -> next;
        while (fast && slow && fast != slow) {
            if (fast->next)
                fast = fast->next->next;
            else
                fast = nullptr;
            slow = slow->next;
        }
        if (fast == slow)
            return true;
        return false;
    }
};

2.python版本

class Solution(object):
    def hasCycle(self, head):
        """
        :type head: ListNode
        :rtype: bool
        """
        if not head or not head.next:
            return False
        fast = head.next.next
        slow  = head.next
        while slow and fast and fast != slow:
            if fast.next:
                fast = fast.next.next
            else:
                fast =  None
            slow = slow.next
        
        if fast == slow:
            return True
        return False
上一篇下一篇

猜你喜欢

热点阅读