LC 160. 相交链表

题目描述

这是 LeetCode 上的 160. 相交链表 ,难度为 简单

给你两个单链表的头节点 headAheadB,请你找出并返回两个单链表相交的起始节点。

如果两个链表没有交点,返回 null

图示两个链表在节点 c1 开始相交:

题目数据 保证 整个链式结构中不存在环。

注意,函数返回结果后,链表必须 保持其原始结构 。

示例 1:

1
2
3
4
5
6
7
输入: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 个节点。

示例 2:

1
2
3
4
5
6
7
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1

输出:Intersected at '2'

解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。
A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

示例 3:

1
2
3
4
5
6
7
输入: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

提示:

  • listA 中节点数目为 m
  • listB 中节点数目为 n
  • $0 <= m, n <= 3 \times 10^4$
  • $1 <= Node.val <= 10^5$
  • $0 <= skipA <= m$
  • $0 <= skipB <= n$
  • 如果 listAlistB 没有交点,intersectVal0
  • 如果 listAlistB 有交点,intersectVal == listA[skipA + 1] == listB[skipB + 1]

进阶:你能否设计一个时间复杂度 $O(n)$ 、仅用 $O(1)$ 内存的解决方案?


模拟

一个朴素的做法是两层循环:当遇到第一个相同的节点时说明找到了,全都走完了还没遇到相同,说明不存在交点。

Java 代码:

1
2
3
4
5
6
7
8
9
10
public class Solution {
public ListNode getIntersectionNode(ListNode a, ListNode b) {
for (ListNode h1 = a; h1 != null ; h1 = h1.next) {
for (ListNode h2 = b; h2 != null ; h2 = h2.next) {
if (h1.equals(h2)) return h1;
}
}
return null;
}
}

C++ 代码:
1
2
3
4
5
6
7
8
9
10
11
class Solution {
public:
ListNode *getIntersectionNode(ListNode *a, ListNode *b) {
for (ListNode* h1 = a; h1 != nullptr ; h1 = h1->next) {
for (ListNode* h2 = b; h2 != nullptr ; h2 = h2->next) {
if (h1 == h2) return h1;
}
}
return nullptr;
}
};

Python 代码(TLE):
1
2
3
4
5
6
7
8
9
10
11
class Solution:
def getIntersectionNode(self, a: ListNode, b: ListNode) -> Optional[ListNode]:
h1 = a
while h1:
h2 = b
while h2:
if h1 == h2:
return h1
h2 = h2.next
h1 = h1.next
return None

TypeScript 代码:
1
2
3
4
5
6
7
8
function getIntersectionNode(a: ListNode | null, b: ListNode | null): ListNode | null {
for (let h1 = a; h1 != null; h1 = h1.next) {
for (let h2 = b; h2 != null; h2 = h2.next) {
if (h1 == h2) return h1;
}
}
return null;
};

  • 时间复杂度:$O(n \times m)$
  • 空间复杂度:$O(1)$

将两条链表分别压入两个栈中,然后循环比较两个栈的栈顶元素,同时记录上一位栈顶元素。

当遇到第一个不同的节点时,结束循环,上一位栈顶元素即是答案。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public ListNode getIntersectionNode(ListNode a, ListNode b) {
Deque<ListNode> d1 = new ArrayDeque(), d2 = new ArrayDeque();
while (a != null) {
d1.addLast(a);
a = a.next;
}
while (b != null) {
d2.addLast(b);
b = b.next;
}
ListNode ans = null;
while (!d1.isEmpty() && !d2.isEmpty() && d1.peekLast().equals(d2.peekLast())) {
ListNode c1 = d1.pollLast(), c2 = d2.pollLast();
ans = c1;
}
return ans;
}
}

C++ 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
ListNode *getIntersectionNode(ListNode *a, ListNode *b) {
deque<ListNode*> d1, d2;
while (a != nullptr) {
d1.push_back(a);
a = a->next;
}
while (b != nullptr) {
d2.push_back(b);
b = b->next;
}
ListNode* ans = nullptr;
while (!d1.empty() && !d2.empty() && d1.back() == d2.back()) {
ListNode* c1 = d1.back(); d1.pop_back();
ListNode* c2 = d2.back(); d2.pop_back();
if (c1 == c2) ans = c1;
}
return ans;
}
};

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution:
def getIntersectionNode(self, a: ListNode, b: ListNode) -> Optional[ListNode]:
d1, d2 = [], []
while a:
d1.append(a)
a = a.next
while b:
d2.append(b)
b = b.next
ans = None
while d1 and d2 and d1[-1] == d2[-1]:
c1, c2 = d1.pop(), d2.pop()
if c1 == c2:
ans = c1
return ans

TypeScript 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function getIntersectionNode(a: ListNode | null, b: ListNode | null): ListNode | null {
let d1 = [], d2 = [];
while (a !== null) {
d1.push(a);
a = a.next;
}
while (b !== null) {
d2.push(b);
b = b.next;
}
let ans = null;
while (d1.length > 0 && d2.length > 0 && d1[d1.length - 1] === d2[d2.length - 1]) {
const c1 = d1.pop()!, c2 = d2.pop()!;
if (c1 === c2) ans = c1;
}
return ans;
};

  • 时间复杂度:$O(n + m)$
  • 空间复杂度:$O(n + m)$

差值法

先对两条链表扫描一遍,取得两者长度,然后让长的链表先走「两者的长度差值」,然后再同时走,遇到第一个节点即是答案。

Java 代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class Solution {
public ListNode getIntersectionNode(ListNode a, ListNode b) {
int c1 = 0, c2 = 0;
ListNode t1 = a, t2 = b;
while (t1 != null && ++c1 > 0) t1 = t1.next;
while (t2 != null && ++c2 > 0) t2 = t2.next;
int t = Math.abs(c1 - c2);
while (t-- > 0) {
if (c1 > c2) a = a.next;
else b = b.next;
}
while (a != null && b != null) {
if (a.equals(b)) {
return a;
} else {
a = a.next; b = b.next;
}
}
return null;
}
}

C++ 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
public:
ListNode *getIntersectionNode(ListNode *a, ListNode *b) {
int c1 = 0, c2 = 0;
ListNode* t1 = a, *t2 = b;
while (t1 != nullptr && ++c1 > 0) t1 = t1->next;
while (t2 != nullptr && ++c2 > 0) t2 = t2->next;
int t = abs(c1 - c2);
while (t-- > 0) {
if (c1 > c2) a = a->next;
else b = b->next;
}
while (a != nullptr && b != nullptr) {
if (a == b) {
return a;
} else {
a = a->next; b = b->next;
}
}
return nullptr;
}
};

Python 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
def getIntersectionNode(self, a: ListNode, b: ListNode) -> Optional[ListNode]:
c1, c2 = 0, 0
t1, t2 = a, b
while t1 and c1 + 1 > 0:
c1 += 1
t1 = t1.next
while t2 and c2 + 1 > 0:
c2 += 1
t2 = t2.next
t = abs(c1 - c2)
while t > 0:
if c1 > c2:
a = a.next
else:
b = b.next
t -= 1
while a and b:
if a == b:
return a
else:
a, b = a.next, b.next
return None

TypeScript 代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function getIntersectionNode(a: ListNode | null, b: ListNode | null): ListNode | null {
let c1 = 0, c2 = 0;
let t1 = a, t2 = b;
while (t1 !== null && ++c1 > 0) t1 = t1.next;
while (t2 !== null && ++c2 > 0) t2 = t2.next;
let t = Math.abs(c1 - c2);
while (t-- > 0) {
if (c1 > c2) a = a?.next;
else b = b?.next;
}
while (a !== null && b !== null) {
if (a === b) {
return a;
} else {
a = a?.next; b = b?.next;
}
}
return null;
};

  • 时间复杂度:$O(n + m)$
  • 空间复杂度:$O(1)$

最后

这是我们「刷穿 LeetCode」系列文章的第 No.160 篇,系列开始于 2021/01/01,截止于起始日 LeetCode 上共有 1916 道题目,部分是有锁题,我们将先把所有不带锁的题目刷完。

在这个系列文章里面,除了讲解解题思路以外,还会尽可能给出最为简洁的代码。如果涉及通解还会相应的代码模板。

为了方便各位同学能够电脑上进行调试和提交代码,我建立了相关的仓库:https://github.com/SharingSource/LogicStack-LeetCode

在仓库地址里,你可以看到系列文章的题解链接、系列文章的相应代码、LeetCode 原题链接和其他优选题解。


本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!