0
点赞
收藏
分享

微信扫一扫

数据结构-链表成环问题总结

谁知我新 2022-02-13 阅读 45

1、找到环的入口

ListNode fast = head,slow = head;

while(true){

    if(fast == null || fast.next == null) {return null;}

    fast = fast.next.next;

    slow = slow.next;

    if(fast == slow ){break;}

}

fast = head;

while(fast != slow) {

    fast = fast.next;

    slow = slow.next;

}

return fast;

2、找到环的长度


if(head == null || head.next == null) {return null;}

ListNode fast = head,slow = head;

do {

    fast = fast.next.next;

    slow = slow.next;

} while(fast != slow);

fast = head;

int len = 0;

while(fast != slow) {

    len++;

    fast = fast.next;

    slow = slow.next;

}

return len;

3、判断链表是否有环

ListNode fast = head,slow = head;

while(fast != null) {

    fast = fast.next;

    if(fast != null){

        fast = fast.next;

    }

    if(fast == slow){

        return true;

    }

    slow = slow.next;

}

return false;
举报

相关推荐

0 条评论