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

      

  • 相关阅读:
    [转]C#汉字转拼音的源码
    [转]C# DES 加密/解密类库,支持文件和中文/UNICODE字符,返回BASE64编码字符串
    48瓶子,48种性格
    “识谎”36计
    巧克力有益智商 经常吃可提高大脑计算能力
    调用方未由服务进行身份验证
    揭秘人体24小时使用手册
    [转]C#实现人民币金额小写转大写的代码
    转一篇绝对详细的手工构造PE文件教程
    bat 查找某个进程的ID号
  • 原文地址:https://www.cnblogs.com/averillzheng/p/3545283.html
Copyright © 2020-2023  润新知