题目地址:
https://leetcode.com/problems/intersection-of-two-linked-lists/
给定两个链表,已知这两个链表有可能从某个节点开始相交,求相交处的节点。
思路是,将一个链表的尾部连到另一个链表的头上,然后用链表求环的算法求解即可。具体说明可参考:https://blog.csdn.net/qq_46105170/article/details/104015181。代码如下:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) {
return null;
}
ListNode tail = headA;
while (tail.next != null) {
tail = tail.next;
}
//将A的尾部连到B的头上
tail.next = headB;
ListNode slow = headA, fast = headA;
do {
slow = slow.next;
if (fast == null || fast.next == null) {
// fast走到了表尾,说明无环,返回null。返回之前要断开
tail.next = null;
return null;
}
fast = fast.next.next;
} while (slow != fast);
// 否则说明有环,则新开一个指针从A的头开始走
ListNode start = headA;
while (start != slow) {
start = start.next;
slow = slow.next;
}
tail.next = null;
return slow;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( 1 ) O(1) O(1)。