LeetCode 02.07. Intersection of Two Linked Lists LCCI

LeetCode 02.07. Intersection of Two Linked Lists LCCI (链表相交)

题目

链接

https://leetcode.cn/problems/intersection-of-two-linked-lists-lcci/

问题描述

给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。

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

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

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

示例

输入: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 个节点。

提示

listA 中节点数目为 m
listB 中节点数目为 n
0 <= m, n <= 3 * 104
1 <= Node.val <= 105
0 <= skipA <= m
0 <= skipB <= n
如果 listA 和 listB 没有交点,intersectVal 为 0
如果 listA 和 listB 有交点,intersectVal == listA[skipA + 1] == listB[skipB + 1]

思路

这题做过的,在哪做的忘了。

两个节点同时向前,如为空,换到另一条上。设长度为a+c和b+c,当走了a+b+c的时候,二者相遇,输出。若不重合,此时为空,同样输出。

复杂度分析

时间复杂度 O(n)
空间复杂度 O(1)

代码

Java

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode ta = headA;
        ListNode tb = headB;
        while (headA != headB) {
            if (headA == null) {
                headA = tb;
            } else {
                headA = headA.next;
            }
            if (headB == null) {
                headB = ta;
            } else {
                headB = headB.next;
            }
        }
        return headA;
    }
```****
posted @ 2022-05-18 15:46  cheng102e  阅读(22)  评论(0编辑  收藏  举报