LeetCode141. Linked List Cycle(环形链表)

141. Linked List Cycle

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.

img

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.

img

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

img


题目:判断给定的链表是否存在环。

思路:Two Pointers.双指针,指针fast每次的步长为2,slow的步长为1。如果链表中存在环,那么fast将先进入环中,slow后进入环中,每次前进更新位置,fast将离slow更近一个位置,最终必将和指针slow相遇。

工程代码下载

/**
 * 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(head == nullptr || head->next == nullptr)
            return false;

        ListNode* slow = head;
        ListNode* fast = head->next;

        while(slow != fast){
            if(fast == nullptr || fast->next == nullptr)
                return false;
            slow = slow->next;
            fast = fast->next->next;
        }
        return true;
    }
};

你可能感兴趣的:(leetcode)