题目 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.
给定两个单链表的头节点 headA
和 headB
,返回两个链表相交的节点。如果两个链表没有相交,则返回 null
。
解题思路
双指针法
使用两个指针 pA
和 pB
分别从 headA
和 headB
开始遍历链表。
当 pA
到达链表末尾时,将其重定向到 headB
;当 pB
到达链表末尾时,将其重定向到 headA
。
如果两个链表相交,pA
和 pB
会在相交节点相遇;如果不相交,pA
和 pB
会同时到达链表末尾(即 null
)。
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}
};class Solution {
public:ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {if (headA == nullptr || headB == nullptr) return nullptr;ListNode *pA = headA;ListNode *pB = headB;while (pA != pB) {pA = (pA == nullptr) ? headB : pA->next;pB = (pB == nullptr) ? headA : pB->next;}return pA;}
};
javascript">class ListNode {constructor(val) {this.val = val;this.next = null;}
}/*** @param {ListNode} headA* @param {ListNode} headB* @return {ListNode}*/
var getIntersectionNode = 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;
};
复杂度分析
-
时间复杂度:
O(m + n)
,其中m
和n
分别是两个链表的长度。两个指针最多遍历m + n
个节点。 -
空间复杂度:
O(1)
,只使用了常数级别的额外空间。