题解 | #判断链表中是否有环#
判断链表中是否有环
https://www.nowcoder.com/practice/650474f313294468a4ded3ce0f7898b9
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 fast = head;
// ListNode slow = head;
// while(fast!=null && fast.next!=null){
// fast = head.next.next;
// slow = head.next;
// if(fast == slow){
// return true;
// }
// }
// return false;
// }
// }
import java.util.Set;
import java.util.HashSet;
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
//如果重复出现说明有环
if (set.contains(head))
return true;
//否则就把当前节点加入到集合中
set.add(head);
head = head.next;
}
return false;
}
}
查看18道真题和解析
美的集团公司福利 727人发布