141. Linked List Cycle, 자바 풀이

이원석·2023년 9월 1일

Leetcode

목록 보기
1/22

[문제]
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.

https://leetcode.com/problems/linked-list-cycle/?envType=study-plan-v2&envId=top-interview-150


/**
 * 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, Integer> map = new HashMap<>();
        ListNode node = head;

        if (node == null) {
            return false;
        }

        while(true) {
            if (map.get(node.next) == null) { 
                map.put(node.next, 1);
            } else if (map.get(node.next) == 1) { // 사이클 발견
                return true;
            } 

            ListNode nextNode = node.next;

            if (nextNode == null) { // 다음 노드가 없다면(사이클 없음)
                return false;
            } else { // 다음 노드가 있다면
                node = nextNode;
            }
        }
    }
}

주어진 연결 리스트에 사이클이 발생하는지를 판별하는 문제이다. 노드를 활용한 기본적인 연결 리스트 구현 역량을 확인하는 문제라고 생각한다.

노드들을 순차적으로 순회하며, HashMap을 사용하여 다음 노드가 이미 탐색했던 노드인지 판별하도록 했다.

ListNode의 메모리 주소를 비교했어야 했는데, 계속해서 val 값을 사용하여 사이클을 확인하느라 조금 애를 먹었다..

0개의 댓글