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;
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容