zoukankan      html  css  js  c++  java
  • LeetCode——Linked List Cycle II

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

    Follow up:

    Can you solve it without using extra space?

    原题链接:https://oj.leetcode.com/problems/linked-list-cycle-ii/

    题目:给定一个链表。返回环開始的节点。如无环。返回null.

    	public ListNode detectCycle(ListNode head) {
    		ListNode fast = head,slow = head;
    		while(fast != null && fast.next != null){
    			slow = slow.next;
    			fast = fast.next.next;
    			if(slow == fast)
    				break;
    		}
    		if(fast == null || fast.next == null )
    			return null;
    		slow = head;
    		while(slow != fast){
    			slow = slow.next;
    			fast = fast.next;
    		}
    		return slow;
    	}
    	// Definition for singly-linked list.
    	class ListNode {
    		int val;
    		ListNode next;
    
    		ListNode(int x) {
    			val = x;
    			next = null;
    		}
    	}

    以下的文章总结得非常好。

    学习了。

    寻找环存在和环入口的方法:

    用两个指针p1、p2指向表头。每次循环时p1指向它的后继,p2指向它后继的后继。

    若p2的后继为NULL,表明链表没有环。否则有环且p1==p2时循环能够终止。此时为了寻找环的入口,将p1又一次指向表头且仍然每次循环都指向后继。p2每次也指向后继。

    当p1与p2再次相等时,相等点就是环的入口。


    參考:http://www.cnblogs.com/wuyuegb2312/p/3183214.html

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    项目管理--项目干系人与组织
    项目管理--项目生命周期概述
    项目管理--简介
    算法学习之冒泡排序,6174问题
    算法学习之基础题
    PHP5.3.8连接Sql Server SQLSRV30
    解决:安装SQl 2008为SQL Server代理服务提供的凭据无效
    Sublime Text2不自动打开最近的项目
    unix网络编程之简介
    算法学习之函数
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4626084.html
Copyright © 2011-2022 走看看