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;
        }
    }
    

      

  • 相关阅读:
    java中Excel导出
    springmvc接收各种参数
    restTemplate使用
    java中io流的操作
    在线Cron表达式生成器
    springBoot实现socketio
    maven的使用
    idea中导入githup项目
    java 单例模式之线程安全的饿汉模式和懒汉模式
    spring定时任务的集中实现
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3545283.html
Copyright © 2011-2022 走看看