leetcode_142:Linked List Cycle

leetcode_142:Linked List Cycle

题目:Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

To represent a cycle in the given linked list, we use an integer pos which represents the position (0-indexed) in the linked list where tail connects to. If pos is -1, then there is no cycle in the linked list.

Note: Do not modify the linked list.

解法1: Fast_Slow_Ptr_Method

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        //note1: Firstly, check the head ptr. 
        if(!head || !head->next) return NULL;
        ListNode* fast = head;
        ListNode* slow = head;
        ListNode* late = head;
        //note2: Here need to check the two steps fast_ptr, It should be mentioned if we use fast&slow ptr to solve problem.
        while((fast->next) && (fast->next->next))
        {
            fast = fast -> next -> next;
            slow = slow -> next;
            
            if(fast == slow)
            {
                while(slow!=late)
                {
                    slow = slow -> next;
                    late = late -> next;
                }
                return slow;
            }
        }
		return nullptr;
    }
};

判断是否存在环的过程用到了快慢指针,快指针两倍于慢指针,快指针和慢指针相遇意味着一定有环存在。之后用先后指针来确定环的其实位置,类似于数学上的追及问题。当快指针和慢指针相遇时,对应的节点指针可能在环上的任一点,假设此时快指针所走的节点个数为2s, 慢指针所走节点个数为s, 两者的差s正好为环所包含节点个数的整数倍。
当快慢指针相遇的同时,启用late指针从head出发,与slow指针相同速度遍历,此时late指针与slow指针相距s个节点,两者的距离查正好是环包含节点个数的整数倍。因此,两指针必定会相遇,由于二者遍历速度相同, 并且,late和slow相遇时,对应的节点指针一定在入环的第一个点

解法1: 利用vector来存储遍历过的位置

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        if(!head) return NULL;
        vector<ListNode*> pos;
        while(head != NULL)
        {
            if(find(pos.begin(), pos.end(), head)== pos.end())
            {
                pos.push_back(head);
                head = head -> next;  
            }
            else
            {
                return head;
            }
        }
        return NULL;
    
    }
};

在该种方法中,用到了vector容器,将元素放到vector中需要调用push_back(); 查找vector中的元素可以调用find(Vec.start(), Vec.end(), key), 该函数返回值为vector中key值对应的地址,*find(Vec.start(), Vec.end(), key)可以表示出key的值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值