zoukankan      html  css  js  c++  java
  • lintcode-103-带环链表 II

    带环链表 II

    给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

    样例

    给出 -21->10->4->5, tail connects to node index 1,返回10

    挑战

    不使用额外的空间

    标签

    链表 两根指针

    思路

    参考lintcode-102-带环链表
    首先,利用快慢指针判断有无环,若遇到slow == fast时,存在环,跳出循环;
    然后,使fast=head,slow不变,slow与fast同步移动,直至再次相遇,即是链表中环的起始节点。

    code

    /**
     * Definition of ListNode
     * class ListNode {
     * public:
     *     int val;
     *     ListNode *next;
     *     ListNode(int val) {
     *         this->val = val;
     *         this->next = NULL;
     *     }
     * }
     */
    class Solution {
    public:
        /**
         * @param head: The first node of linked list.
         * @return: The node where the cycle begins. 
         *           if there is no cycle, return null
         */
        ListNode *detectCycle(ListNode *head) {
            // write your code here
            ListNode * fast = head, *slow = head, *result = NULL;
    
            while(fast != NULL && fast->next != NULL) {
                slow = slow->next;
                fast = fast->next->next;
    
                if(fast == slow) {
                    break;
                }
            }
            
            if(fast != NULL && fast->next != NULL) {
                fast = head;
                while(fast != slow) {
                    slow = slow->next;
                    fast = fast->next;
                }
                result = fast;
            }
            return result;
        }
    };
    
  • 相关阅读:
    模块安装
    yagmail 邮件模块
    unittest 单元测试
    用 yaml 写测试用例
    nnlog 日志模块
    Jenkins安装以及邮件配置
    数据驱动之 python + requests + Excel
    url 编码解码
    15. 测试环境部署-linux
    vue使用UEditor富文本编辑器
  • 原文地址:https://www.cnblogs.com/libaoquan/p/7168416.html
Copyright © 2011-2022 走看看