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?

    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) {
     *         val = x;
     *         next = null;
     *     }
     * }
     */
    public class Solution {
        public ListNode detectCycle(ListNode head) {
            ListNode entry = null;
    		boolean flag = true;
    		if(head != null){
    			ListNode speedOne = head;
    			ListNode speedTwo = head;
    			if(head.next != null){
    				speedOne = speedOne.next;
    				if(speedOne.next != null)
    					speedTwo = speedOne.next;
    				else
    					flag = false;
    			}
    			else
    				flag = false;
    			while(flag){
    				if(speedOne == speedTwo)
    					break;
    				else{
    					speedOne = speedOne.next;
    					if(speedTwo != null && speedTwo.next != null){
    						speedTwo = speedTwo.next;
    						speedTwo = speedTwo.next;
    					}
    					else{
    						flag = false;
    						break;
    					}
    				}
    			}
    			if(flag){
    				speedOne =  head;
    				while(speedOne != speedTwo){
    					speedOne = speedOne.next;
    					speedTwo = speedTwo.next;
    				}
    				entry = speedOne;
    			}
    			else
    				entry = null;
    		   
    	    }
    	    return entry;
        }
    }
    

      

     rewrite the code as the following:

    public class Solution {
        public ListNode detectCycle(ListNode head) {
           //find the intersection ListNode of speed one and speed two
    		ListNode intersectNode = null;
    		if(head != null && head.next != null){
    			ListNode speedOne = head;
    			ListNode speedTwo = head.next;
    			while(speedTwo != null){
    				if(speedOne == speedTwo)
    					break;
    				
    				speedOne = speedOne.next;
    				speedTwo = speedTwo.next;
    				if(speedTwo != null)
    					speedTwo = speedTwo.next;
    			}
    		
    			//Once speedTwo meets speedOne, we reset speedOne to head and change 
    			//the speed of speedTwo to one
    			if(speedTwo != null){
    				speedOne = head;
    				speedTwo = speedTwo.next;
    				while(speedOne != speedTwo){
    					speedOne = speedOne.next;
    					speedTwo = speedTwo.next;
    				}
    				intersectNode = speedOne;
    			}
    		}
    		return intersectNode;
        }
    }
    

      

  • 相关阅读:
    Windows CE Notification API的使用方法
    探讨如何成为技术团队管理者
    Android应用---基于NDK的samples例程hello-jni学习NDK开发
    在eclipse中配置android ndk的自动编译环境builders
    用javah 导出类的头文件, 常见的错误及正确的使用方法
    Android下NDK开发环境搭建
    Android系统修改硬件设备访问权限
    Android调试工具之ADB
    关于前端小白的一点小建议
    Vue.js简单实践
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3545283.html
Copyright © 2011-2022 走看看