跳至主要內容

141. 环形链表

T4mako算法哈希表链表双指针小于 1 分钟

141. 环形链表

解法一:Set 存储

public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet<ListNode> set = new HashSet<>();
        while (head != null){
            if(!set.add(head)) return true; // add() 未添加成功返回 false
            head = head.next;
        }
        return false;
    }
}

解法二:快慢指针

定义一个快指针一个慢指针,如果有环,快指针和满指正会相遇

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }
}
评论
  • 按正序
  • 按倒序
  • 按热度
Powered by Waline v2.15.5