141. Linked List Cycle
Question
The given head, the linked list head, determines whether the linked list has a cycle.
A loop exists in a linked list if there is any node in the list that can be reached again by continuously tracking the next pointer. Internally, pos is used to indicate the index of the node to which the next tail pointer is attached. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a loop in the linked list where the end connects to the 1st node (index 0).
Example 2:
Input: head = [1,2], pos = 0
Output: true
Explanation: There is a loop in the linked list where the end connects to the 0th node.
Example 3:
Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Solution
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL) return false;
unordered_map m;
while(head->next!=NULL){
if(m[head]) return true;
m[head]++;
head = head->next;
}
return false;
}
};
Comments
Post a Comment