LeetCode 面试题52. 两个链表的第一个公共节点

题目链接:https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/

输入两个链表,找出它们的第一个公共节点。

如下面的两个链表:

 

在节点 c1 开始相交。

输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
输出:Reference of the node with value = 8
输入解释:相交节点的值为 8 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
 

输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
输出:Reference of the node with value = 2
输入解释:相交节点的值为 2 (注意,如果两个列表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

输入:intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2
输出:null
输入解释:从各自的表头开始算起,链表 A 为 [2,6,4],链表 B 为 [1,5]。由于这两个链表不相交,所以 intersectVal 必须为 0,而 skipA 和 skipB 可以是任意值。
解释:这两个链表不相交,因此返回 null。

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     struct ListNode *next;
 6  * };
 7  */
 8 struct ListNode *getIntersectionNode(struct ListNode *headA, struct ListNode *headB) {
 9     int la=0,lb=0;
10     struct ListNode *q=headA,*p=headB;
11     while(q){
12         la++;
13         q=q->next;
14     }
15     while(p){
16         lb++;
17         p=p->next;
18     }
19     if(la>lb){
20         int t=la-lb;
21         while(t--){
22             headA=headA->next;
23         }
24         while(headA&&headB){
25             if(headA==headB){
26                 return headA;
27             }else{
28                 headA=headA->next;
29                 headB=headB->next;
30             }
31         }
32         return NULL;
33     }else{
34         int t=lb-la;
35         while(t--){
36             headB=headB->next;
37         }
38         while(headA&&headB){
39             if(headA==headB){
40                 return headA;
41             }else{
42                 headA=headA->next;
43                 headB=headB->next;
44             }
45         }
46         return NULL;
47     }
48 }

猜你喜欢

转载自www.cnblogs.com/shixinzei/p/12372621.html
今日推荐