您的位置:首页 > 其它

[Leetcode 160, Easy] Intersection of Two Linked Lists

2015-01-25 11:06 471 查看
Problem:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:
A:          a1 → a2
                   ↘
                     c1 → c2 → c3
                   ↗            
B:     b1 → b2 → b3


begin to intersect at node c1.

Notes:

If the two linked lists have no intersection at all, return
null
.
The linked lists must retain their original structure after the function returns.
You may assume there are no cycles anywhere in the entire linked structure.
Your code should preferably run in O(n) time and use only O(1) memory.

Analysis:
The solution to this problem has two parts. For the first part, we use two pointers, starting from the head of each linked lists, to run to the last node of each linked lists. If they point to a same node, the two linked lists
share some same nodes.

Record the pointer of the last entry. And, then, set the tail of the shared part of two linked lists to the head of one of linked lists. Use the tracing method, i.e., set two pointers, all of which comes from the head of another
head of the linked lists, one run one step once, and the other one run two steps once. Then must meed some place in the cycle. Set the faster one to the head again, and let two pointers run with the pace (one step / time). They must meet at the inter section
of two linked lists. (The proof of this can be refered in the problme of "Cycle of linked list")

We should recover the tail conncection, since we record the pointer of the last node.

Solutions:

C++:

ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(headA == NULL || headB == NULL)
            return NULL;

        ListNode* pLast = NULL;
        ListNode* pCurA = headA;
        ListNode* pCurB = headB;
        while(1) {
            if(pCurA->next == NULL) {
                pLast = pCurA;
                break;
            }
            pCurA = pCurA->next;
        }
        while(1) {
            if(pCurB->next == NULL) {
                if(pCurB != pLast)
                    return NULL;
                break;
            }
            pCurB = pCurB->next;
        }
        
        pLast->next = headA;
        
        ListNode* pSlow = headB->next;
        ListNode* pFast = headB->next->next;
        while(pSlow != pFast) {
            pSlow = pSlow->next;
            pFast = pFast->next->next;
        }
        
        pFast = headB;
        while(pFast != pSlow) {
            pSlow = pSlow->next;
            pFast = pFast->next;
        }
        pLast->next = NULL;
        return pSlow;
    }


Java:

Python:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: