当前位置:   article > 正文

链表 面试题 02.08. 环路检测 (快慢指针)_快慢指针三倍还能在环形链表相遇吗

快慢指针三倍还能在环形链表相遇吗

快慢指针理解

分析:如果链表中有环,快慢指针肯定能相遇,这个非常容易证明,而且相遇肯定是在环中.
快指针走的倍数是慢指针两倍,这样可以非常容易得出循环的开始结点

证明(我想画个图,不想写,看图更好理解 不难)下面快指针走的是2a+2b,笔误

在这里插入图片描述

c语言解答

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {
    //直接判断是否没有结点,或者只有一个节点,直接返回
    if(head==NULL||head->next==NULL){
        return NULL;
    }

    //申请快慢指针,快指针是慢指针走的倍数是两倍
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast!=NULL&&fast->next!=NULL){
        slow=slow->next;
        fast=fast->next->next;
        //两指针相遇说明有环,namename就可以开始把其中一个指针初始为头,然后开始一步一步走直到相遇,返回相遇的结点就行
        if(fast==slow){
            fast=head;
            while(fast!=slow){
                fast=fast->next;
                slow=slow->next;
            }
            return slow;
        }
    }  
    return NULL;  
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38

java解答

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null||head.next==null)
            return null;
        ListNode slow=head;
        ListNode fast=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            slow=slow.next;
            if(fast==slow){
                fast=head;
                while(fast!=slow){
                    fast=fast.next;
                    slow=slow.next;
                }
                return fast;
            }
        }
        return null;
        
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

总结

还是直接套套路就行.

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家自动化/article/detail/895246
推荐阅读
相关标签
  

闽ICP备14008679号