码迷,mamicode.com
首页 > 其他好文 > 详细

Intersection of Two Linked Lists

时间:2015-01-08 22:34:23      阅读:284      评论:0      收藏:0      [点我收藏+]

标签:

该题目对内存的使用极其变态。所用变量不能超过4个。否侧会内存超限。解法有两个,其中第二种解法,内存还需要优化,否则会内存越界。

解法一:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
         ListNode* tempA = headA;ListNode* tempB = headB;
         int countA=0,countB=0;
		 
		 if(headA == NULL || headB == NULL)
		   return NULL;
		 while(tempA->next != NULL)
		 {
		     countA++;
			 tempA = tempA->next;
		 }
		 while(tempB->next != NULL)
		 {
		     countB++;
			 tempB = tempB->next;
		 }
		 if(tempA != tempB)
		 	return NULL;
		 if(countA > countB)
		 {
		 
		   	int count = countA- countB;
			while(count>0)
		    {
              headA = headA->next;
			  count--;
		    }

		 }
		 
		 else
		 {
            int count = countB - countA;
			while(count>0)
		    {
              headB = headB->next;
			  count--;
		    }

		 }
		 while(headA != headB)
		 {
              headA = headA->next;
			  headB = headB->next;
		 }
		 return headA;
		  
        
    }
   
};

 解法二:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
          ListNode * endA;
		  if(headA == NULL || headB == NULL)
		  return NULL;
		  endA = getEnd(headA);
		  endA->next = headA;

		  bool ret ;
		  ListNode * pmeetpoint = NULL;
		  ret = RoundCircle(headB,&pmeetpoint);
		  if(ret == false)
		  return NULL;	
		  ListNode *presult;

		  presult = GetEntry(headB,pmeetpoint);
		  endA->next = NULL;
		  return presult;
		  
        
    }
   ListNode* GetEntry(ListNode *headA, ListNode *pmeetpoint)
   {
       while(headA != pmeetpoint)
       {
           headA = headA->next;
		   pmeetpoint = pmeetpoint->next;
	   }
      return headA;
   }
   ListNode * getEnd(ListNode *headA)
   {
      while(headA->next != NULL)
      {
            headA= headA->next;
	  }
	  return headA;

   }
   bool RoundCircle(ListNode *headB,ListNode** ppmeetpoint)
   {
        ListNode * pslow,*pquick;
		pslow  =  headB;
		pquick =  headB;
		while(1)
		{
		
		  if(pquick->next ==NULL)
		  	return false;
		  pquick = pquick->next;
		  if(pquick->next ==NULL)
		  	return false;
		  pquick = pquick->next;
		  pslow = pslow->next;

		  if(pslow == pquick)
		  {
             *ppmeetpoint = pslow;
		     return true;

		  }
		  	
		  	

		}


   }
};

  

 

Intersection of Two Linked Lists

标签:

原文地址:http://www.cnblogs.com/xgcode/p/4211916.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!