LeetCode-160. Intersection of Two Linked Lists

问题描述

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1:

The test cases are generated such that there are no cycles anywhere in the entire linked structure.

Note that the linked lists must retain their original structure after the function returns.

解答

解法一

先通过遍历得到两个链表的长度,进而得到链表长度的差值n,设置两个指针,先让长链表上的指针往前走n步,然后两个指针再同步向前遍历,当两个指针的值相等的时候,就到了交叉节点。

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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/*
* @Description: 160. Intersection of Two Linked Lists
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @description: 方法一:双指针长度比较法
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
const getIntersectionNode = function (headA, headB) {
if (headA === null || headB === null) {
return null
}
let lenA = getListLen(headA)
let lenB = getListLen(headB)
let fast = null
let slow = null
if (lenA > lenB) {
let n = lenA - lenB
fast = headA
slow = headB
while (n > 0) {
fast = fast.next
n--
}
} else {
let n = lenB - lenA
fast = headB
slow = headA
while (n > 0) {
fast = fast.next
n--
}
}
while ((fast !== null) && (slow !== null) && (fast !== slow)) {
fast = fast.next
slow = slow.next
}
return fast
}

function getListLen (head) {
let n = 0
let p = head
while (p !== null) {
p = p.next
n++
}
return n
}
解法二

两个链表上的指针同步向前遍历,到达尾部后,互相连接到对方链表的头部,继续遍历,两个指针第一次相遇的节点就是公共节点。

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
/*
* @Description: 160. Intersection of Two Linked Lists
* @Author: libk
* @Github: https://github.com/libk
*/
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @description: 方法二:双指针连接法
* @param {ListNode} headA
* @param {ListNode} headB
* @return {ListNode}
*/
const getIntersectionNode1 = function (headA, headB) {
if (headA === null || headB === null) {
return null
}
let pA = headA
let pB = headB

while (pA !== pB) {
pA = (pA === null) ? headB : pA.next
pB = (pB === null) ? headA : pB.next
}
return pA
}