首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。