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

  • 相关阅读:
    Go断后,Dart冲前,Google的野心
    gcc dynamic load library
    Go http server 高并发
    还是Go 为了伟大的未来
    windows go dll 框架
    Go cookie
    Go web ajax project
    hdoj 2844 Coins
    hdoj 1203 I NEED A OFFER!
    hdoj 2546 饭卡
  • 原文地址:https://www.cnblogs.com/chuiyuan/p/4764691.html
Copyright © 2011-2022 走看看