0%

面试题02.07 intersection-of-two-linked-lists-lcci

链表相交

题目

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

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

思路

求出两个链表长度之差,将长链表前进gap个步,之后可以同时进行比较。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode* cur_a = headA;
ListNode* cur_b = headB;
int len_a = 0,len_b =0;
while(cur_a != NULL){
cur_a = cur_a->next;
len_a ++;
}
while(cur_b != NULL){
cur_b = cur_b->next;
len_b++;
}
cur_a = headA;
cur_b = headB;
if(len_b > len_a){
swap(len_a,len_b);
swap(cur_a,cur_b);
}
int gap = len_a - len_b;
while(gap--){
cur_a = cur_a->next;
}
while(cur_a != NULL){
if(cur_a == cur_b){
return cur_a;
}
cur_a = cur_a->next;
cur_b = cur_b->next;
}
return NULL;
}
};