首页 > Java > java教程 > 正文

检查LinkedList中的循环

WBOY
发布: 2024-07-17 19:00:15
原创
418 人浏览过

Check Loop in LinkedList

问题

//tc :O(N) N is the length of the linkedList
//sc:(1) constant space complexity
/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        //we can use double jump to find if loop is present in the loop
        if(head ==null || head.next ==null) return false;
        ListNode node1 = head;
        ListNode node2 = head.next;
        while(node1!=null && node2!=null){
            if(node1==node2) return true;
            node1 = node1.next;
            node2  = node2.next ==null ? null : node2.next.next;
        }
        return false;
    }
}
登录后复制

以上是检查LinkedList中的循环的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!