문제링크 - https://leetcode.com/problems/linked-list-cycle/?envType=study-plan-v2&envId=top-interview-150
pos
는 -1 또는 링크드리스트의 유효한 위치이다.ListNode
가 주어졌을 때 순환이 있으면 true
없으면 false
를 반환.해당 문제는 토끼와 거북이 방법을 사용하면 쉽게 풀 수 있다.
두 node의 속도를 다르게 다음 노드를 참조하게 되었을 때, 순환하지 않는다면 먼저 간 노드가 끝(null)에 도달하지만, 만약 순환한다면 늦게 참조하는 노드와 빨리 참조하는 노드가 만나게 될 것이다.
문제에서 입력이 들어오는 데이터는 ListNode head
이다. 해당 노드를 시작으로 두 노드를 움직여 위치를 비교할 수 있다.
fast
slow
ListNode fast = head;
ListNode slow = head;
빠르게 옮기던 node가 끝에 도달하여 다음 노드가 없을 떄 까지 slow와 fast 노드를 이동시킨다. 단, fast는 두칸씩 빠르게 이동한다.
만약 순환한다면 반복문을 꼐속 돌아 언젠간 slow와 fast의 위치가 같아진다.
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
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) {
ListNode fast = head;
ListNode slow = head;
while(fast!=null && fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast){
return true;
}
}
return false;
}
}
시간 복잡도
공간 복잡도