Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* 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<ListNode> hashSet = new HashSet<>();
while(head != null){
if(hashSet.contains(head)) return true;
hashSet.add(head);
head = head.next;
}
return false;
}
}
总结:本题目要找出是否为循环链表,首先确定出判断条件,如果遍历到最后为null,不是循环链表, 如果遍历到最后等于head;本体可以利用hashSet的特性,没有重复的元素,hash.contains()方法一样方便。