zoukankan      html  css  js  c++  java
  • 链表中是否有环以及环的位置

    package swordoffer;
    
    public class Loop <AnyType>{
    	private static class Node <AnyType>{
    		public Node<AnyType> next ;
    		public AnyType data ;
    		
    		public Node(Node<AnyType> next , AnyType data){
    			this.next = next ;
    			this.data = data ;
    		}
    	}
    	boolean hasCircle (Node<AnyType> head ){
    		Node fast = head ,slow = head ;
    		Node<AnyType> encounter ;
    		
    		while (fast!=null && fast.next!= null){
    			fast = fast.next.next ;
    			slow = slow.next ;
    			if (fast== slow){
    				encounter = fast ;//用在后面
    				return true ;
    			}
    		}
    		encounter = null ;
    		return false ;
    	}
    	
    	/**
    	 * s +nr =2s 
    	 * s = x+y
    	 * 得到
    	 * nr = x+y 
    	 * x =nr-y 
    	 * 也就是说,p1 从链表 开始处遍历,p2从encounter处遍历,一次都 移动 一步,则当p1到达入口点时,p2移动nr-y步
    	 * 两者恰好在环的入口 点处相遇了。
    	 * @param head
    	 * @param encounter
    	 * @return
    	 */
    	Node<AnyType> findEntry (Node<AnyType> head , Node<AnyType> encounter) {
    		Node<AnyType> p1 = head , p2 = encounter ;
    		while(p1!= p2 ){
    			p1= p1.next ;
    			p2 = p1.next ;
    		}
    		return p1 ;
    	}
    
    }
    

    参考 了

    http://blog.csdn.net/wuzhekai1985/article/details/6725263

  • 相关阅读:
    C#4.0,支持动态语言?
    宁波.NET俱乐部第二次聚会WCF讲稿
    在线学习新编程
    mysql常用函数
    PHP 连接Mysql数据库
    Unix网络编程进阶计划
    RabbitMQ 安装
    Golang 变量
    Golang 结构体
    Golang 指针
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4764691.html
Copyright © 2011-2022 走看看