141.环形链表。2星

#题目:给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。
输入:head = [3,2,0,-4], pos = 1
输出:true
解释:链表中有一个环,其尾部连接到第二个节点。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
方法一:

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
         if(head == null) return false;
        ArrayList<ListNode> ans = new ArrayList<>();
        ans.add(head);
        while(head.next!=null)
        {
            if(ans.contains(head.next)) return true;
            head=head.next;
            ans.add(head);
        }
        return false;
    }
}

使用一个ListNode类型的ArrayList链表,来记录遍历过给节点,如遍历到重复节点,则说明发现环。
.contains(a):如果a存在列表中,则返回true,否则false。

方法二:

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null || head.next.next == null) {
            return false;
        }//如果head链表无元素,或只有一个元素,或有两个不构成环的元素,返回false
        // 一个一步,一个两步,若有环,迟早会相遇
        //若链表有三个及以上元素或两个元素组成的有环链表,进行下面操做
        ListNode stepOne = head.next;
        // 不能直接head.next.next,防止head.next为空
        ListNode stepTwo = head.next;
        while (stepOne != null && stepTwo != null) {//当这两个节点指向不为空的情况下
            stepTwo = stepTwo.next;//stepTwo每次多走一步,如果有环,则stepTwo迟早能追上stepOne
            if (stepTwo == null) {
                return false;
            }
            if (stepOne == stepTwo) {
                return true;
            }
            stepOne = stepOne.next;
            stepTwo = stepTwo.next;
        }
        return false;
    }
}

快慢指针法。
学习别人的代码。
作者:staywithmelyj
链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/java-hao-shi-0msnei-cun-xiao-hao-zhan-sheng-97-kua/
来源:力扣(LeetCode)

方法三:

public boolean hasCycle(ListNode head) {
    Set<ListNode> nodesSeen = new HashSet<>();//存在哈希表中记录,判断有无,与方法一思想类似,但不使用Arraylist而是哈希表,速度有明显提升,略慢与快慢指针法
    while (head != null) {
        if (nodesSeen.contains(head)) {
            return true;
        } else {
            nodesSeen.add(head);
        }
        head = head.next;
    }
    return false;
}

作者:LeetCode
链接:https://leetcode-cn.com/problems/linked-list-cycle/solution/huan-xing-lian-biao-by-leetcode/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

发布了18 篇原创文章 · 获赞 0 · 访问量 332

猜你喜欢

转载自blog.csdn.net/qq_44787671/article/details/104442285