1.NC4 判断链表中是否有环
判断链表中是否有环_牛客题霸_牛客网 (nowcoder.com)
解法1
经典的解法是使用双指针-快慢指针,快指针走两步,满指针走一步,如果两个指针刚好相遇,那么链表存在环。
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 || head.next == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && fast.next != null) {
fast = fast.next.next;
slow = slow.next;
if (fast == slow) {
return true;
}
}
return false;
}
}
解法2
使用HashSet,set是去重的,每次add(node)之前和之后记录set的长度,如果两次的长度一样说明没有添加成功,那么链表中有环
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 || head.next == null) {
return false;
}
HashSet<ListNode> set = new HashSet<>();
ListNode node = head;
while(node != null){
int len1 = set.size();
set.add(node);
int len2 = set.size();
if(len1 == len2){
return true;
}else node = node.next;
}
return false;
}
}