Algorithm/연결리스트
리트코드 141. Linked List Cycle // 플로이드 사이클 검사
Mini_96
2025. 6. 4. 13:52
https://leetcode.com/problems/linked-list-cycle/description/
풀이1
/**
* 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) {
HashMap<ListNode,Boolean> m = new HashMap<>();
while(head!=null){
if(m.containsKey(head)){
return true;
}
else{
m.put(head,true);
}
head=head.next;
}
return false;
}
}
풀이2 (플로이드 사이클)
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode rabbit = head;
ListNode tutle = head;
while(rabbit!=null && rabbit.next!=null){
tutle = tutle.next;
rabbit = rabbit.next.next;
if(tutle==rabbit){
return true;
}
}
return false;
}
}