LeetCode Daily Question 25
May 8th 2022
5 月 8 日 每日一题
题目:141. 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 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.
思路
两种思路,快慢指针和 hashmap/set,hashmap 需要注意 value 可能重复所以 key 应该使用 ListNode*类型。快慢指针需要考虑 head 为 nullptr,linkList 只有两个的 edge case(建议提前列出 0 1 2 3 个 Node 的情况。
需要注意的是,unorder_map 的 count 函数,如果该 key 存在,返回 1,不存在返回 0。
代码
1 | /** |