Leetcode - 142. Linked List Cycle II

숲사람·2022년 7월 27일
0

멘타트 훈련

목록 보기
102/237

문제

링크드 리스트의 head만 주어진다. 만약 리스트에 사이클이 존재한다면 사이클이 시작되는 노드를 리턴하라. 사이클이 없다면 NULL리턴

https://leetcode.com/problems/linked-list-cycle-ii/

유사문제

Leetcode - 141. Linked List Cycle

해결

해시 테이블 사용

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        unordered_map<ListNode *, int> table;
        while (head) {
            if (table[head])
                return head;
            table[head]++;
            head = head->next;
        }
        return NULL;
    }
};
profile
기록 & 정리 아카이브 용도 (보다 완성된 글은 http://soopsaram.com/documentudy)

0개의 댓글