0
点赞
收藏
分享

微信扫一扫

LeetCode-141-环形链表

佳简诚锄 2021-09-28 阅读 53
LeetCode

环形链表

解法一:Set去重
import java.util.HashSet;
import java.util.Set;

public class LeetCode_141 {
    public static boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        Set<ListNode> appeared = new HashSet<>();
        while (head != null) {
            if (!appeared.add(head)) {
                return true;
            }
            head = head.next;
        }
        return false;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        System.out.println(hasCycle(head));
    }
}
举报

相关推荐

0 条评论