[Data Structure OJ Question] Ring Linked List

Original title link: https://leetcode.cn/problems/linked-list-cycle/description/

Table of contents

1. Description of the topic

2. Thinking analysis

3. Code implementation


1. Description of the topic

2. Thinking analysis

The overall idea: define the fast and slow pointers fast and slow . If the linked list does have a ring , the fast pointer will catch up with the slow pointer in the ring.

That is, the slow pointer moves one step at a time, and the fast pointer moves two steps at a time. The two pointers start to run from the starting position of the linked list. If the linked list has a ring, they will definitely meet in the ring, otherwise the fast pointer will go to the end of the linked list first.

Let's simplify this problem, use a line segment to represent the linked list without the ring part in front, and use a circle to represent the linked list with the ring part.

3. Code implementation

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode *fast=head,*slow=head;
    while(fast&&fast->next)
    {
        fast=fast->next->next;
        slow=slow->next;
        if(slow==fast)
            return true;
    }
    return false;
}

Guess you like

Origin blog.csdn.net/m0_62531913/article/details/132352203