lintcode-带环链表II

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

/**
 * 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
        
        if(head == NULL || head->next == NULL) { return NULL; }
        
        ListNode * front = head;
        ListNode * tail = head;
        
        while(front && front->next) {
            front = front->next->next;
            tail = tail->next;
            
            if(front == tail) {
                break;
            }
        }
        
        if(front && front == tail) {
            front = head;
            while(front != tail && front != NULL && tail != NULL) {
                front = front->next;
                tail= tail->next;
            }
            
            return front;
        } else {
            return NULL;
        }
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,923评论 18 139
  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 5,165评论 0 12
  • 【声明】欢迎转载,但请保留文章原始出处→_→文章来源:http://www.jianshu.com/p/08d08...
    梦工厂阅读 3,787评论 3 31
  • 转载请注明出处:http://www.jianshu.com/p/c65d9d753c31 在上一篇博客《数据结构...
    Alent阅读 3,535评论 4 74
  • 距离发表上篇文章,已经好久了,期间一度让我怀疑自己的能力已经无可救药,哪怕一直在鼓励自己。 是的,我很优秀。再鼓励...
    想做一个输出者阅读 257评论 0 0