Ring linked list practice


insert image description here

foreword

This article is a special linked list of the linked list--the topic of the circular linked list, and the topics range from simple to difficult

1. Ring linked list

1. Topic introduction

The topic is in 141. Circular linked list
insert image description here

2. Ideas

insert image description here

Assume that when the fast pointer enters the entrance of the ring at the slow pointer, the distance between slow and the entrance X is L+X+nR( ) nR就是一个循环,不影响相遇, and the distance traveled by slow is L.
Assume that slow takes x steps at each step, and slow takes 2x steps. Then the difference between the two is x steps. If you walk t times in total,
then the difference between the two is xt times, x is a unit, so xt can be any number, then it can be equal to X so
the two can always meet

3. Code

bool hasCycle(struct ListNode *head) {
    
    
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast&&fast->next)
    {
    
    
        fast=fast->next->next;
        slow=slow->next;
        if(slow==fast)
        {
    
    
            return true;
        }

    }
    return false;
}

2. Ring linked list II

1. Solution

Topic in Circular Linked List II
insert image description here

2. Ideas

On the basis of the previous question
insert image description here

insert image description here

So we have this conclusion

让一个指针从链表起始位置开始遍历链表,同时让一个指针从环的相遇点的位置开始绕环
运行,两个指针都是每次均走一步,最终肯定会在入口点的位置相遇

3. Code

struct ListNode *detectCycle(struct ListNode *head) {
    
    
    struct ListNode *fast,*slow;
    fast=slow=head;
    while(fast&&fast->next)
    {
    
    
        fast=fast->next->next;
        slow=slow->next;
        if(slow==fast)
        {
    
    
            struct ListNode *mid=slow;//mid记录相遇点
            slow=head;
            while(mid!=slow)//mid从从相遇点出发,slow从起点出发
            {
    
    
             mid=mid->next;
             slow=slow->next;
            }
            return slow;
        }
    }
    return NULL;
   
    
}

Guess you like

Origin blog.csdn.net/Ruiren_/article/details/129758633