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.
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
Example 2:Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where the tail connects to the 0th node.
Example 3:Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.
Constraints:
The number of the nodes in the list is in the range [0, 104].
-105 <= Node.val <= 105
pos is -1 or a valid index in the linked-list.
Follow up: Can you solve it using O(1) (i.e. constant) memory?
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题目大意:
给定一个链表,判断链表是否成环。
实现思路:
利用快慢指针,当两个指针重合的时候,即说明这个链表成环了。
实现代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* t1=head;
ListNode* t2=head;
if(head&&!head->next) return false;
while(t1&&t2){
if(!t2||!t2->next) return false;
t1=t1->next;
t2=t2->next->next;
if(t1==t2) return true;
}
return false;
}
};
看了官方代码,知道还有一种解法,即利用哈希表,检测一个元素是否重复出现。
代码如下:
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> seen;
while(head){
if(seen.count(head)) return true;
seen.insert(head);
head=head->next;
}
return false;
}
};
不过这种方法似乎要慢一些。
通过这道题,我学到了几种方法:
1、快慢指针。
2、哈希表的解法,利用unordered_set来存储每一个结点,并利用count函数检测是否有重复的结点被加入unordered_set中。