leetcode No.141 circular linked list

topic

Link: https: //leetcode-cn.com/problems/linked-list-cycle

Given a list, the list is determined whether a ring.

To show the list given ring, we integer pos connected to the end of the list to represent the position of the list (index starts from 0). If pos is -1, no ring on this list.

Example 1:

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

Output: true

Explanation: the list has a ring tail portion connected to a second node.

Example 2:

Input: head = [1,2], pos = 0

Output: true

Explanation: the list has a ring, which is connected to the tail of the first node.

Example 3:

Input: head = [1], pos = -1

Output: false

Explanation: The list does not ring.

Advanced:

You can use O (1) (ie, constant) memory to solve this problem?

C ++ code

Ideas: Use pointer speed

The mobile node a pointer to a slow

A two node pointer moves fast

Once the fast pointer is NULL, there is no ring, because it can be found at the end of

If there is a ring, then the whole cycle is endless, the pointer will soon overtake slower pointer, and will not be missed.

/**
 * 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 == NULL || head->next == NULL)
            return false;
        ListNode* slow = head;
        ListNode* fast = head->next;
        while(slow != fast){
            if(fast->next == NULL || fast->next->next == NULL)
                return false;
            fast = fast->next->next;
            slow = slow->next;
        }
        return true;
    }
};

When execution: 16ms, defeated 54.04% of all users to submit in C ++

Memory consumption: 9.8MB, defeated 33.30% of all users to submit in C ++

Published 98 original articles · won praise 353 · views 540 000 +

Guess you like

Origin blog.csdn.net/u011583927/article/details/104742058