zoukankan      html  css  js  c++  java
  • 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;
    
    	}
    };


  • 相关阅读:
    DHCP服务的配置(linux)
    LVM逻辑卷
    python的元素列表
    DOS和DDOS你知道多少?
    DOS与DDOS攻击的原理与防范之法
    常见HTTP状态代码,http报错代码翻译
    TCP和UDP优缺点
    DLL何时需共享内存管理器
    Delphi 指针大全
    Delphi编写DLL(以及静态和动态方式调用)
  • 原文地址:https://www.cnblogs.com/xlert/p/3960433.html
Copyright © 2011-2022 走看看