Given a linked list, determine if it has a cycle in it. To represent a cycle in the given linked list, we use an integer Example 1: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where tail connects to the second node. Example 2: Input: head = [1,2], pos = 0 Output: true Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: false Explanation: There is no cycle in the linked list. Follow up: Can you solve it using O(1) (i.e. constant) memory? |
给定一个链表,判断链表中是否有环。 为了表示给定链表中的环,我们使用整数 示例 1: 输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。 示例 2: 输入:head = [1,2], pos = 0 输出:true 解释:链表中有一个环,其尾部连接到第一个节点。 示例 3: 输入:head = [1], pos = -1 输出:false 解释:链表中没有环。 进阶: 你能用 O(1)(即,常量)内存解决此问题吗? |
思路:
第一种:可以使用哈希表,将每个元素存入当前哈希表,看 最后一个元素的下一个节点是否在哈希表中,如果再返回false
第二种:适合题意,也就是常亮内存。快慢链表思路,一个走一步一个两步,若快节点或快节点下一个 为空则返回false,当个快慢节点相遇则返回true
/**
* 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) {
//if(!head) return false;
ListNode *quick=head,*slow=head;
while(quick && quick->next)
{
slow=slow->next;
quick=quick->next->next;
if(slow==quick) return true;
}return false;
}
};