본문 바로가기
Algorithm

[leetCode 141] Linked List Cycle (JAVA)

by ddahu 2023. 8. 28.

1.문제

Linked List Cycle - LeetCode

 

Linked List Cycle - LeetCode

Can you solve this real interview question? 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 continuo

leetcode.com


2.문제설명

 

이 문제는 주어진 ListNode 가 순회하고 있는지 체크하는 문제이다.


3.소스코드

public class Solution {
    public boolean hasCycle(ListNode head) {
       ListNode slow=head;
       ListNode fast=head;
        while(fast!=null && fast.next!=null)
        {
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast)
            {
                return true;
            }
        }
        return false;
    }
}

4.소스코드 설명

 

이 문제는 주어진 노드들의 순환을 확인 하는 문제이다.  순환을 확인 하기 위해서 가장 많이 쓰는 Floyd 순회 알고리즘 을 사용 하여 두개의 포인터를 사용하여 리스트의 순환을 찾았다.

 

slow 는 다음 한칸 , fast 는 두칸 씩 노드를 확인하여 순환을 확인 하게 한다.

 

만약에 fast 를 조회하는데 null 이라면 순회하지 않는 것을 확인 할 수 있다.


 

5.회고

 

연결 리스트를 자주 사용하지 않아 잊어 먹고 있었던 알고리즘 이였다. 하지만 계속 순회를 생각해보면 기억이 날정도로 간단한 알고리즘이여서 이 문제도 간단하게 풀었다.