Created
September 13, 2018 19:25
-
-
Save yokolet/20d1d167ee6d269df150a3e526f080ca to your computer and use it in GitHub Desktop.
Intersection of Two Linked Lists
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| Description: | |
| Write a program to find the node at which the intersection of two singly linked lists begins. | |
| - If the two linked lists have no intersection at all, return null. | |
| - The linked lists must retain their original structure after the function returns. | |
| - You may assume there are no cycles anywhere in the entire linked structure. | |
| - Your code should preferably run in O(n) time and use only O(1) memory. | |
| Example: | |
| Input: | |
| A: a1->a2 \ | |
| +->c1->c2->c3 | |
| B: b1->b2->b3 / | |
| Output: c1 | |
| """ | |
| def getIntersectionNode(headA, headB): | |
| """ | |
| :type head1, head1: ListNode | |
| :rtype: ListNode | |
| """ | |
| if headA is None or headB is None: | |
| return None | |
| cur_a = headA | |
| cur_b = headB | |
| while cur_a != cur_b: | |
| cur_a = cur_a.next if cur_a else headB | |
| cur_b = cur_b.next if cur_b else headA | |
| return cur_a |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment