带环链表2

描述

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

样例

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

代码实现

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: The node where the cycle begins. 
     *           if there is no cycle, return null
     */
    public ListNode detectCycle(ListNode head) {  
        if (head == null || head.next == null) {
            return null;
        }
        ListNode fast = head.next;
        ListNode slow = head;
        while (fast != slow) {
            if (fast == null || fast.next == null) {
                return null;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        /**while (head != fast.next) {
            head = head.next;
            slow = fast.next;
        }**/
//用慢指针的next与head比较
        while (head != slow.next) {
            head = head.next;
            slow = slow.next;
        }
        return head;
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 1 序 2016年6月25日夜,帝都,天下着大雨,拖着行李箱和同学在校门口照了最后一张合照,搬离寝室打车去了提前租...
    RichardJieChen阅读 10,630评论 0 12
  • 转载请注明出处:http://www.jianshu.com/p/c65d9d753c31 在上一篇博客《数据结构...
    Alent阅读 8,837评论 4 74
  • 第一章 Nginx简介 Nginx是什么 没有听过Nginx?那么一定听过它的“同行”Apache吧!Ngi...
    JokerW阅读 32,922评论 24 1,002
  • 一 雨打夜孤城 路驰车马声 只影探虚空 何处一盏灯 二 蜀地云难阔 花艳香欲沉 此间鲲鹏志 岂告蜩鸠闻
    姚大可阅读 3,477评论 0 0
  • 劳动,成就生活之美 文/蔚兰 早起,看到一个环卫工老大爷正在用条帚打扫着街道。他年纪已经有些大了,但身体看起来还非...
    空谷幽兰7666阅读 3,816评论 0 4

友情链接更多精彩内容