From a859520173a93d775e67c4818d20153eecf2baca Mon Sep 17 00:00:00 2001 From: fulcrum999 <114816542+fulcrum999@users.noreply.github.com> Date: Sat, 1 Oct 2022 19:35:08 +0530 Subject: [PATCH] Created intersection-of-two-linked-lists.cpp Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. --- C++/intersection-of-two-linked-lists.cpp | 26 ++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 C++/intersection-of-two-linked-lists.cpp diff --git a/C++/intersection-of-two-linked-lists.cpp b/C++/intersection-of-two-linked-lists.cpp new file mode 100644 index 00000000..5252b669 --- /dev/null +++ b/C++/intersection-of-two-linked-lists.cpp @@ -0,0 +1,26 @@ +// 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. + +// Time: O(m + n) +// Space: O(1) + +/** + * Definition for singly-linked list. + * struct ListNode { + * int val; + * ListNode *next; + * ListNode(int x) : val(x), next(NULL) {} + * }; + */ + +class Solution { +public: + ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) { + ListNode *curA = headA, *curB = headB; + while (curA != curB) { + curA = curA ? curA->next : headB; + curB = curB ? curB->next : headA; + } + return curA; + } +};