欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 资讯 > C++/JavaScript ⭐算法OJ⭐ 链表相交

C++/JavaScript ⭐算法OJ⭐ 链表相交

2025/2/23 5:31:15 来源:https://blog.csdn.net/Vitalia/article/details/145789001  浏览:    关键词:C++/JavaScript ⭐算法OJ⭐ 链表相交

题目 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:
intersection of Two Linked Lists

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.

给定两个单链表的头节点 headAheadB,返回两个链表相交的节点。如果两个链表没有相交,则返回 null

解题思路

双指针法

使用两个指针 pApB 分别从 headAheadB 开始遍历链表。

pA 到达链表末尾时,将其重定向到 headB;当 pB 到达链表末尾时,将其重定向到 headA

如果两个链表相交,pApB 会在相交节点相遇;如果不相交,pApB 会同时到达链表末尾(即 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;}
};
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),其中 mn 分别是两个链表的长度。两个指针最多遍历 m + n 个节点。

  • 空间复杂度:O(1),只使用了常数级别的额外空间。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词