首页 > 代码库 > Intersection of Two Linked Lists

Intersection of Two Linked Lists

该题目对内存的使用极其变态。所用变量不能超过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