Given a linked list, return the node where the cycle begins. If there is no cycle, return To represent a cycle in the given linked list, we use an integer Note: Do not modify the linked list. Example 1: Input: head = [3,2,0,-4], pos = 1 Output: tail connects to node index 1 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: tail connects to node index 0 Explanation: There is a cycle in the linked list, where tail connects to the first node. Example 3: Input: head = [1], pos = -1 Output: no cycle Explanation: There is no cycle in the linked list. Follow up: |
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 为了表示给定链表中的环,我们使用整数 说明:不允许修改给定的链表。 示例 1: 输入:head = [3,2,0,-4], pos = 1 输出:tail connects to node index 1 解释:链表中有一个环,其尾部连接到第二个节点。 示例 2: 输入:head = [1,2], pos = 0 输出:tail connects to node index 0 解释:链表中有一个环,其尾部连接到第一个节点。 示例 3: 输入:head = [1], pos = -1 输出:no cycle 解释:链表中没有环。 进阶: |
思路:和上一题一样
第一种:哈希表,所有元素放入哈希表,最后一个元素下一个元素在哈希表中,就返回 哈希表元素,缺点是空间 大
第二种:快慢指针,slow走一步,quick 走两步,若quick或者quick->next为空则不存在环,如果碰头,就是有环,然后 一个指针从环这里,另一个指针从head开始,每个 走一步,知道最终 两个相遇就是要的交点
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *quick=head,*slow=head;
while(quick && quick->next)
{
slow=slow->next;
quick=quick->next->next;
if(slow == quick) break;
}
if(!quick || !quick->next) return NULL;
slow = head;
while(slow!=quick)
{
slow=slow->next;
quick=quick->next;
}return quick;
}
};