题目
分析
判断链表中有没有环,可以将链表依次遍历。存储到HashSet中,判断是否有结点重复,从而判断是否有环,但是这种方式时间复杂度太高。采用快慢指针,可以更快速的得到答案。
代码
借助于HashSet
/**
* 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) {
Set<ListNode>set=new HashSet<>();
while(head!=null){
head=head.next;
if(set.contains(head))
return true;
set.add(head);
}
return false;
}
}
快慢指针: 快指针每次走两步,慢指针每次走一步, 若有环,必定会相遇。主要是注意循环的判断条件,不要出现空指针异常。
/**
* 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 quickNode=head.next, slowNode=head;
while(quickNode!=null&&quickNode.next!=null){
if(slowNode==quickNode)
return true;
slowNode=slowNode.next;
quickNode=quickNode.next.next;
}
return false;
}
}