[leetcode]Intersection of Two Linked Lists寻找两链表的公共节点

来源:互联网 发布:买淘宝店铺哪个网站 编辑:程序博客网 时间:2024/06/16 09:14

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.
题目意思:求两链表的第一个公共节点出现的位置,并把该位置的节点返回。
notes:
如果两个链表根本没有交集,返回null。
链表函数返回后,保留其原有的结构返回。
你可以假设没有循环在整个地方的连接结构。
您的代码应该优选地运行在O(n)时间和O(1)的存储。
解题思路:
1. 把链表变换为反向链表,通过比较最后两个链表的节点值的不同来搜索出第一个公共节点,但与题目给出的要求“保留原有结构不符”
2. 若两个链表的最后一个元素相等,则这两个链表一定存在公共节点,也许公共节点是最后第二个,也许是链表中间的某一个节点,让长的链表先移动abs(sizeA-sizeB)距离,让headA与headB的长度一致,这样就容易比较两个链表并寻的第一个公共节点。
如下为思路2的C代码,比较冗余:

/** * 解题思路:headA与headB的链表长度有三种情况,1. headA长度比headB长 2. headA长度比headB短  3.headA的长度 == headB的长度 * 若两个链表的最后一个元素ListNODE是相等的,说明这两个链表一定相等,只是不清楚相等的第一个元素在链表的那个位置 *所以我们可以采取如下思路:长的链表先移动abs(sizeA-sizeB)个节点,这样headA与headB一样长,就可以进行两链表直接对比 * 寻找节点相等的公共节点 * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {    int i,sizeA,sizeB;    int sub = 0;    struct ListNode *A, *B;    A = headA;    B = headB;    if(headA == NULL || headB == NULL){        return NULL;    }    sizeA = 1;    while(headA->next != NULL){        sizeA++;        headA = headA->next;    }    sizeB = 1;    while(headB->next != NULL){        sizeB++;        headB = headB->next;    }    if(headA->val == headB->val){        if(sizeA > sizeB){            sub = sizeA - sizeB;            for(i = 0; i < sub; i++){                A = A->next;            }        }else if(sizeA < sizeB){            sub = sizeB - sizeA;            for(i = 0; i < sub; i++){                B = B->next;            }        }        while(A != NULL && B != NULL){            if(A->val == B->val){                return A;            }else{                A = A->next;                B = B->next;            }        }    }else{        return NULL;    }}
0 0