zoukankan      html  css  js  c++  java
  • [LeetCode]Link 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?

    思考:第一步:设环长为len,快慢指针q、p相遇时,q比p多走了k*len。
            第二部:p先走k*len步,p,q一起走每次一步,相遇时p比q多走了一个环距离,此时q就是环开始结点。

            通过分析AC的感觉真好!

    class Solution {
    public:
        ListNode *detectCycle(ListNode *head) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
            if(!head||!head->next) return NULL;
    		ListNode *p=head;int countP=0;
    		ListNode *q=p->next;int countQ=1;
    		bool flag=false;
    		int len=0;
    		while(q&&q->next)
    		{
    			if(p==q)
    			{
    				len=countQ-countP;
    				flag=true;
    				break;
    			}
    			else
    			{
    				q=q->next->next;
    				p=p->next;
    				countP+=1;
    				countQ+=2;
    			}
    
    		}
    		if(flag)
    		{
    			p=head;
    			q=head;
    			while(len--)
    			{
    				p=p->next;
    			}
    			while(p!=q)
    			{
    				p=p->next;
    				q=q->next;
    			}
    			return p;
    		}
    		else return NULL;
        }
    };
    

      

  • 相关阅读:
    delete误删除恢复
    oracle自增字段
    oracle唯一约束
    linux得到系统当前日期
    to_char+fm
    oracle范围分区
    oracle之use_hash用法
    oracle11g的regexp函数
    第一个脚本输入参数
    使用ctl将txt或csv文件导入表数据
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3426608.html
Copyright © 2011-2022 走看看