zoukankan      html  css  js  c++  java
  • 142. Linked List Cycle II

    欢迎fork and star:Nowcoder-Repository-github

    142. Linked List Cycle II

    题目

     Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
    
    Note: Do not modify the linked list.
    
    Follow up:
    Can you solve it without using extra space? 
    
    

    解答

    • 解析
    - my solution is like this: using two pointers, one of them one step at a time. another pointer each take two steps. Suppose the first meet at step k,the length of the Cycle is r. so..2k-k=nr,k=nr
    Now, the distance between the start node of list and the start node of cycle is s. the distance between the start of list and the first meeting node is k(the pointer which wake one step at a time waked k steps).the distance between the start node of cycle and the first meeting node is m, so...s=k-m,
    s=nr-m=(n-1)r+(r-m),here we takes n = 1..so, using one pointer start from the start node of list, another pointer start from the first meeting node, all of them wake one step at a time, the first time they meeting each other is the start of the cycle.
    
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    // Linked List cycle-ii
    class Solution {
    public:
    	ListNode *detectCycle(ListNode *head) {
    		if (!head||!head->next)
    		{
    			return NULL;
    		}
    		ListNode* slow=head;
    		ListNode* fast=head;
    
    		bool isCycle = false;
    		while (fast&&fast->next)
    		{
                slow = slow->next;
    			fast = fast->next->next; 
    			if (slow==fast)
    			{
    				isCycle = true;
    				break; //has cycle 第一次退出
    			}
    			
    		}
    
    		if (!isCycle)
    		{
    			return NULL;
    		}
    		else
    		{
    			ListNode* first = head;
    			while (first!=slow)
    			{
    				first = first->next;
    				slow = slow->next;
    			}
    		}
    		return slow;
    	}
    };
    
    

    题目来源

  • 相关阅读:
    小数据池,深浅拷贝以及集合
    字典
    列表,元组以及range
    整型,布尔值以及字符串详解
    while循环,格式化输出,运算符及编码初识
    Python简介以及入门
    码云以及Git的使用
    JaveScript——简介、语法
    网页练习
    HTML_css样式表 样式属性 格式布局
  • 原文地址:https://www.cnblogs.com/ranjiewen/p/8093166.html
Copyright © 2011-2022 走看看