Fork me on github

141 环形链表

双指针

public class Solution {
    public boolean hasCycle(ListNode head) {
        //双指针,一个快,一个慢,快慢指针相遇说明链表有循环
        if(head == null || head.next == null){
            return false;
        }
        //下面至少有两个节点
        ListNode slow = head;
        ListNode fast = head.next;
        while(fast != slow){
            if(fast == null || fast.next == null){
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}

哈希表

import java.util.HashSet;
import java.util.Set;

public class Solution {
    public boolean hasCycle(ListNode head) {
        //哈希表
        Set<ListNode> set = new HashSet<>();
        while(head != null){
            if(set.contains(head)){
                return true;
            }
            else{
                set.add(head);
            }
            head = head.next;
        }
        return false;
    }
}
posted @ 2020-08-21 17:32  zjy4fun  阅读(78)  评论(0编辑  收藏  举报