|
| 1 | +''' |
| 2 | +
|
| 3 | +Write a program to find the node at which the intersection of two singly linked lists begins. |
| 4 | +
|
| 5 | +For example, the following two linked lists: |
| 6 | +
|
| 7 | +
|
| 8 | +begin to intersect at node c1. |
| 9 | +
|
| 10 | +
|
| 11 | +
|
| 12 | +Example 1: |
| 13 | +
|
| 14 | +
|
| 15 | +Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3 |
| 16 | +Output: Reference of the node with value = 8 |
| 17 | +Input Explanation: The intersected node's value is 8 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [4,1,8,4,5]. From the head of B, it reads as [5,0,1,8,4,5]. There are 2 nodes before the intersected node in A; There are 3 nodes before the intersected node in B. |
| 18 | +
|
| 19 | +
|
| 20 | +Example 2: |
| 21 | +
|
| 22 | +
|
| 23 | +Input: intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1 |
| 24 | +Output: Reference of the node with value = 2 |
| 25 | +Input Explanation: The intersected node's value is 2 (note that this must not be 0 if the two lists intersect). From the head of A, it reads as [0,9,1,2,4]. From the head of B, it reads as [3,2,4]. There are 3 nodes before the intersected node in A; There are 1 node before the intersected node in B. |
| 26 | +
|
| 27 | +
|
| 28 | +Example 3: |
| 29 | +
|
| 30 | +
|
| 31 | +Input: intersectVal = 0, listA = [2,6,4], listB = [1,5], skipA = 3, skipB = 2 |
| 32 | +Output: null |
| 33 | +Input Explanation: From the head of A, it reads as [2,6,4]. From the head of B, it reads as [1,5]. Since the two lists do not intersect, intersectVal must be 0, while skipA and skipB can be arbitrary values. |
| 34 | +Explanation: The two lists do not intersect, so return null. |
| 35 | +
|
| 36 | +
|
| 37 | +Notes: |
| 38 | +
|
| 39 | +If the two linked lists have no intersection at all, return null. |
| 40 | +The linked lists must retain their original structure after the function returns. |
| 41 | +You may assume there are no cycles anywhere in the entire linked structure. |
| 42 | +Your code should preferably run in O(n) time and use only O(1) memory. |
| 43 | +
|
| 44 | +''' |
| 45 | + |
| 46 | + |
| 47 | + |
| 48 | +# Definition for singly-linked list. |
| 49 | +# class ListNode(object): |
| 50 | +# def __init__(self, x): |
| 51 | +# self.val = x |
| 52 | +# self.next = None |
| 53 | + |
| 54 | +class Solution(object): |
| 55 | + def getIntersectionNode(self, headA, headB): |
| 56 | + """ |
| 57 | + :type head1, head1: ListNode |
| 58 | + :rtype: ListNode |
| 59 | + """ |
| 60 | + |
| 61 | + # Approach one 循环两次,消除相交点之前的长度差 |
| 62 | + if not headA or not headB : return None |
| 63 | + p1, p2 = headA, headB |
| 64 | + while(p1 != p2): |
| 65 | + p1 = headB if not p1 else p1.next |
| 66 | + p2 = headA if not p2 else p2.next |
| 67 | + return p1 |
0 commit comments