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

      

  • 相关阅读:
    SecureCRT使用提示
    毕业论文写作时,那些页眉、页脚中的内容中的横线、回车符难删除问题解决
    ostu进行遥感图像的分割
    有关奇葩的mex编程时的matlab出现栈内存错误的问题
    free 一个指针时【 retval = HeapFree(_crtheap, 0, pBlock);】报错的原因
    matlab坐标轴设置
    Use PRODUCT_USER_PROFILE To Limit User
    mysql只导出表结构或数据
    编程学习要讲究效率和经验
    Unity3D的SerializeField 序列化域名
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3545283.html
Copyright © 2020-2023  润新知