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
.
ListNode
의 head
가장 먼저 떠오른 자료구조 Set 를 이용한다.
해결 전략
null
일 경우 false
를 반환true
를 반환public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> nodes = new HashSet<>();
ListNode currentNode = head;
while (currentNode != null) {
if (nodes.contains(currentNode)) {
return true;
}
nodes.add(currentNode);
currentNode = currentNode.next;
}
return false;
}
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
Floyd's Cycle Detection Algorithm
null
을 만나게 될 경우, 해당 Linked List는 순환하지 않는다.해결 전략
moving1
, moving2
에 각각 head
, head.next
를 가리킨다.moving1
, moving2
가 각각 한 개, 두 개 node씩 이동하면 아래 과정을 반복한다.moving2
가 null을 가리키게 될 경우, false
를 반환한다.true
를 반환한다.public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null) {
return false;
}
ListNode moving1 = head;
ListNode moving2 = head.next;
while (moving2 != null) {
if (moving1 == moving2) {
return true;
}
moving1 = moving1.next;
moving2 = doublyNextNode(moving2);
}
return false;
}
private ListNode doublyNextNode(ListNode node) {
ListNode nextNode = node.next;
if (nextNode == null) {
return null;
}
return nextNode.next;
}
}
/**
* 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) {
ListNode s = head;
ListNode f = head;
while(f != null && f.next != null){
s = s.next;
f = f.next.next;
if(s == f){
return true;
}
}
return false;
}
}