美文网首页
Java算法(5):链表是否有环

Java算法(5):链表是否有环

作者: starryxp | 来源:发表于2021-01-13 10:11 被阅读0次

    龟兔指针:
    龟指针slowPtr每次后移1个结点。兔指针fastPtr每次后移2个结点

    ListNode findLinkedListLoopBegin(ListNode head){
    if(head==null){
    return null;
    }
    ListNode slowPtr=head;
    ListNode fastPtr=head;
    boolean isLinkedListContainsLoop=false;
    while(slowPtr.next!=null && fastPtr.next.next!=null){
    slowPtr=slowPtr.next;
    fastPtr=fastPtr.next.next;
    if(slowPtr==fastPtr){
    isLinkedListContainsLoop=true;
    break;
    }
    }
    if(isLinkedListContainsLoop){
    slowPtr=head;
    while(slowPtr!=fastPtr){
    slowPtr=slowPtr.next;
    fastPtr=fastPtr.next;
    }
    return slowPtr;
    }
    return null;
    }

    相关文章

      网友评论

          本文标题:Java算法(5):链表是否有环

          本文链接:https://www.haomeiwen.com/subject/amlcvktx.html