LeetCode刷题_160. Intersection of Two Linked Lists

原题链接:https://www.acwing.com/activity/content/problem/content/8/1/
Notes:
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.

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        if headA == None or headB == None:
            return None
        cur_1 = headA
        cur_2 = headB
        len_A = 0
        len_B = 0
        while cur_1:
            cur_1 = cur_1.next
            len_A += 1
            
        while cur_2:           
            cur_2 = cur_2.next
            len_B += 1
            
        cur_1 = headA
        cur_2 = headB
        
        if len_A>len_B:
            for i in range(len_A - len_B):
                cur_1 = cur_1.next
        else:
            for i in range(len_B - len_A):
                cur_2 = cur_2.next

        while cur_1 != cur_2:
            cur_1 = cur_1.next
            cur_2 = cur_2.next
        return cur_1
            

你可能感兴趣的:(编程练习)