• LeetCode题目:Linked List Cycle II


        这个题目,首先应当找出环内任意一点:俩指针,一快一慢(走一步,走两步),重合就是环内节点。

        然后将问题转化为经典问题:寻找链表交叉节点位置。

        P.S. 创建了一个GitHub项目,目前已经更新了大概十道题:https://github.com/xlinc/CrackingLeetCode.git

    class Solution {
    public:
    	ListNode *detectCycle(ListNode *head) {
    		if (head == NULL)
    			return NULL;
    		ListNode *p1 = head, *p2 = head->next;
    		if ( p2 == NULL)
    			return NULL;
    		if (p2 == head)
    		{
    			return head;
    		}
    		while (p1 != p2)
    		{
    			p1 = p1->next;
    			if (p2->next != NULL){
    				if (p2->next == head)
    					return head;
    				p2 = p2->next;
    				if (p2->next != NULL){
    					if (p2->next == head)
    						return head;
    					p2 = p2->next;
    				}
    				else
    					return NULL;
    			}
    			else
    				return NULL;
    		}
    		p1 = head;
    		ListNode* innerNode = p2;
    		//cout <<"innerNode: "<< innerNode->val << endl;
    		ListNode* checkNode = innerNode->next;
    	
    		int len1 = 0, len2 = 0;
    		do{
    			len1++;
    			p2 = p2->next;
    		} while (p2 != innerNode);
    
    		//cout << len1 << endl;
    
    		do{
    			len2++;
    			p1 = p1->next;
    		} while (p1 != innerNode);
    
    		p1 = (len1 > len2 ? innerNode : head);
    		p2 = (len1 > len2 ? head : innerNode);
    		for (int i = 0; i < abs(len1-len2); i++)
    		{
    			p1 = p1->next;
    		}
    		while (p1!= p2)
    		{
    			p1 = p1->next;
    			p2 = p2->next;
    		}
    		return p1;
    
    	}
    };


  • 相关阅读:
    CENTOS7下安装REDIS
    金融量化之tushare模块的使用
    fiddler抓包出现错误 creation of the root certificate was not successful
    matplotlib学习
    Android-消息处理学习总结(Handler,Looper)
    Android-View的绘制源码学习总结
    数据库练习
    编译原理实验一
    图形学
    资源分配(分组背包)
  • 原文地址:https://www.cnblogs.com/xlert/p/3960433.html
Copyright © 2020-2023  润新知