leetcode题141. 环形链表

95 阅读1分钟

leetcode地址:leetcode.cn/problems/li…

原题描述

给你一个链表的头节点 head ,判断链表中是否有环。

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos 不作为参数进行传递 。仅仅是为了标识链表的实际情况。

如果链表中存在环 ,则返回 true 。 否则,返回 false 。

进阶:使用o(1) 常量级内存解决。

解题思路:

思路1: 循环链表,将每次访问到的元素存入集合中,每次获取到元素判断集合中是否存在该元素,如果存在则说明有环,如果遍历链表遇到null说明无环。

代码如下:

public class Solution {
    public boolean hasCycle(ListNode head) {
        //方法1 记录到达过的节点 每次到达进行比对
        HashMap<ListNode, Boolean> map = new HashMap<>();
        while(head!=null){
            Boolean bool = map.get(head);
            if(bool==null||!bool){
                map.put(head,Boolean.TRUE);
            }else{
                return true;
            }
            head = head.next;
        }
        return false;
    }
}

好提交,一次过。 但是用时和空间消耗都很高。

思路2: 双指针之快慢指针,让一个指针跑的快,一个指针跑的慢,跑的快的到了跑到慢的后面或者相同的位置,则说明有环。

代码如下:

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode index = head;
        while(head!=null){
            head = head.next.next;
            index = index.next;
            if(head==index){
                return true;
            }
        }
        return false;
    }
}

提交,发现NullPointException,第三个案例没过,因为只有一个节点,所以head.next.next会报错。

加上逻辑,head.next之后,判断head.next是否为null值。

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode index = head;
        while(head!=null){
            head = head.next;
            if(head==null){
                return false;
            }
            head = head.next;
            index = index.next;
            if(head==index){
                return true;
            }
        }
        return false;
    }
}

再提交,通过。