160. Intersection of Two Linked Lists

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;
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容