美文网首页
160. Intersection of Two Linked

160. Intersection of Two Linked

作者: YellowLayne | 来源:发表于2017-06-22 11:20 被阅读0次

    1.描述

    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.

    2.分析

    较长的List先走n步(n为两个List长度的差值),然后依次比较两个List的指针是否相同。

    3.代码

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
        if (NULL == headA || NULL ==headB) return NULL;
        struct ListNode *longList = headA;
        struct ListNode *shortList = headB;
        unsigned int lenA = 0;
        unsigned int lenB = 0;
        while (longList != NULL) {
            ++lenA;
            longList = longList->next;
        }
        while (shortList != NULL) { 
            ++lenB;
            shortList = shortList->next;
        }
        longList = lenA >= lenB ? headA : headB;
        shortList = lenA >= lenB ? headB : headA;
        int gap = lenA >= lenB ? lenA - lenB : lenB - lenA;
        for (unsigned int i = 0; i < gap; ++i) {
            longList = longList->next;
        }
        while (NULL != longList && NULL != shortList) {
            if (longList == shortList) return longList;
            longList = longList->next;
            shortList = shortList->next;
        }
        return NULL;
    }
    

    相关文章

      网友评论

          本文标题:160. Intersection of Two Linked

          本文链接:https://www.haomeiwen.com/subject/waaxcxtx.html