BM6 判断链表中是否有环(牛客)

题目链接

判断链表中是否有环_牛客题霸_牛客网

题目

BM6 判断链表中是否有环(牛客)_第1张图片

BM6 判断链表中是否有环(牛客)_第2张图片

解题思路

法一哈希表(使用HashSet存储出现的指针,如果在此出现说明存在环) 法二快慢指针(若快指针追上慢指针,说明存在环)

代码

法一哈希表

import java.util.*;
/**
 * 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) {
        HashSet st=new HashSet<>();
        while(head!=null){
            if(st.contains(head)){
                return true;
            }
            st.add(head);
            head=head.next;
        }
        return false;
    }
}

法二快慢指针

import java.util.*;
/**
 * 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;
        ListNode late,fast;
        late=head;
        fast=head;
        while(fast!=null&&fast.next!=null){
            fast=fast.next.next;
            late=late.next;
            if(fast==late) return true;
        }
        return false;
    }
}

你可能感兴趣的:(数据结构与算法,(Java牛客面试刷题),链表,算法,数据结构)