160. Intersection of Two Linked Lists

题目要求:

Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:

A: ''''''''''''''' a1 → a2
'''''''''''''''''''''''''''''''''''''''''' ↘
''''''''''''''''''''''''''''''''''''''''''''''''c1 → c2 → c3
'''''''''''''''''''''''''''''''''''''''''' ↗
B: b1 → b2 → b3

Notions:
  • 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.
解题思路:
  • headA和headB是后对齐方式,那么求headA、headB的长度,较长的那个链表前面多余的一定是没用的,所以将较长的链表从较短链表对齐的地方开始同时遍历,会使问题变得简化。
  • 但是,求链表长度的Time: O(n)=m+n,遍历的Time: O(n)=2·n,所以总体的Time:O(n)=m+3·n
# 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
        """
        def get_length(head):
            length = 0
            while head:
                head = head.next
                length = length + 1
            return length
        
        list_A_len = get_length(headA)
        list_B_len = get_length(headB)
        
        if list_A_len > list_B_len:
            detla = list_A_len - list_B_len
            while detla:
                headA = headA.next
                detla = detla - 1
            
        else:
            detla = list_B_len - list_A_len
            while detla:
                headB = headB.next
                detla = detla - 1
        
        while 1:
            if headA == headB:
                return headA
            headA = headA.next
            headB = headB.next
            
        return None

问题:
# a->c->b->c
# b->c->a->c
这两个链表怎么办???

你可能感兴趣的:(160. Intersection of Two Linked Lists)