Link : Linked List Cycle
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.



pos is -1 or a valid index in the linked-list.import java.util.HashSet;
// Definition for singly-linked list.
class ListNode2 {
int val;
ListNode2 next;
ListNode2(int x) {
val = x;
next = null;
}
}
public class LC6 {
// public boolean hasCycle(ListNode2 head) {
// HashSet<ListNode2> indices = new HashSet<>();
// ListNode2 now = head;
// while (now!=null){
// if (indices.contains(now))){
// return true;
// }
// indices.add(now);
// now = now.next;
// }
// return false;
// }
public boolean hasCycle(ListNode head) {
while (head != null) {
if (head.val > 100000) {
return true;
}
head.val = 100001;
head = head.next;
}
return false;
}
}
-10^5 <= Node.val <= 10^5라는 부분이 있어 값을 Node.val이 가질 수 있는 값보다 1만큼 큰 값으로 변경하여 이미 지나온 노드를 표기하였다.