Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

160. 相交链表 #61

Open
Geekhyt opened this issue Aug 5, 2021 · 2 comments
Open

160. 相交链表 #61

Geekhyt opened this issue Aug 5, 2021 · 2 comments
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Aug 5, 2021

原题链接

双指针

  1. 借助双指针分别遍历链表 A 和 B。
  2. 遍历完自己后再将头指针指向另一个链表头部,继续遍历。
  3. 如果存在交点,则一定会相遇。
const getIntersectionNode = function(headA, headB) {
    if (headA === null || headB === null) {
        return null
    }
    let pA = headA, pB = headB
    while (pA !== pB) {
        pA = pA === null ? headB : pA.next
        pB = pB === null ? headA : pB.next
    }
    return pA
}
  • 时间复杂度:O(m + n)
  • 空间复杂度:O(1)
@Geekhyt Geekhyt added the 简单 label Aug 5, 2021
@eavan5
Copy link

eavan5 commented Sep 23, 2021

if (headA === null || headB === null) {
        return null
    }

这一句应该不用判断的,如果其中一个是null,他们走一遍之后必定是null相等

@Geekhyt
Copy link
Owner Author

Geekhyt commented Sep 23, 2021

if (headA === null || headB === null) {
        return null
    }

这一句应该不用判断的,如果其中一个是null,他们走一遍之后必定是null相等

需要的,如果其中一个是 null,那么一定不相交,就没有必要“走一遍”咯。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants