首頁 > Java > java教程 > 主體

檢查LinkedList中的循環

WBOY
發布: 2024-07-17 19:00:15
原創
317 人瀏覽過

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學習者快速成長!