-
[LeetCode] 141. Linked List CycleLeetCode 2021. 10. 13. 23:33728x90
https://leetcode.com/problems/linked-list-cycle/
Linked List Cycle - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
Linked List Cycle


Linked List가 하나 주어진다.
이때 이 Linked List가 끝이 있는지 아니면 앞쪽으로 연결되어 싸이클이 만들어지는지 판단하는 문제다.
Easy 문제라 매우매우 쉽다.
리스트 포인터를 저장하는 set을 만들어준 뒤,
한번씩 훑으며 set에 겹치는 포인터가 들어오면 true를,
포인터가 NULL을 가리키면 false를 리턴해주면 된다.
풀이는 아래와 같다.
class Solution { public: bool hasCycle(ListNode *head) { set<ListNode*> s; ListNode* cur = head; while (cur && cur->next) { if (s.find(cur)!=s.end()) return true; s.insert(cur); cur = cur->next; } return false; } };'LeetCode' 카테고리의 다른 글
[LeetCode] 189. Rotate Array (0) 2021.10.14 [LeetCode] 279. Perfect Squares (0) 2021.10.14 [LeetCode] 1008. Construct Binary Search Tree from Preorder Traversal (0) 2021.10.13 [LeetCode] 201. Bitwise AND of Numbers Range (0) 2021.10.10 [LeetCode] 212. Word Search II (0) 2021.10.09