141_环形链表

141_环形链表

 

 

package 链表;
import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode-cn.com/problems/linked-list-cycle/
 * 
 * @author Huangyujun 方法二:快慢指针法 生活常识:操场跑圈,跑得快的最终会追上跑得慢的
 */
public class _141_环形链表 {
    /**
     * 方法一: 使用 HashSet 实现不重复的添加 【Set 集合特点:不重复】
     * @param head
     * @return
     */
    public boolean hasCycle1(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while (head != null) {
            if (!seen.add(head)) { // HashSet 底层是HashMap(添加元素时会判断是否已经存在,已经存在会添加不成功)
                return true;
            }
            head = head.next;
        }
        return false;
    }


    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null)
            return false;
        ListNode slow = head;
        ListNode fast = head.next;
        while (fast != null && fast.next != null) {
//            if(slow == fast)    return true;        //调整到后面,因为刚进来肯定是不会相等的
            slow = slow.next;
            // 等式 右边
            // 为什么 fast.next 不能为空,例如其为空的话 fast.next.next 就变成 null.next 报错!
            // 为什么 fast 不能为空,看等式左边 fast = null 的情况
            fast = fast.next.next;
            if (slow == fast)
                return true;
        }
        return false;
    }
}

 

posted @ 2021-12-19 22:21  一乐乐  阅读(25)  评论(0编辑  收藏  举报