Intersection of Two Linked Lists两链列的交叉

Easy

寻找两个链列的交叉。

Example, A,B两个链列

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
在c1节点交叉

注意:
如果两个链列没有交叉,返回null;
两个链列的结构不能变动;
可以假设链列无环;
时间复杂度O(n),存储O(1)

Solution

链列结构不能变动,可以构建指针。问题的难点在于两个链列的长度可能是不同的,LeetCode的coder提供了一个非常有意思的思路,通过变换指针的头,可以对冲两个链列的长度不同导致的问题。

首先建立两个指针a, b分别指向headA和headB。逐步推进a, b, 如果出现a==b的情况那么就找到headA和headB的交叉链了,但是这种情况只有在headA和headB长度相同的情况下才会出现。而事实是headA和headB长度往往不同,没有关系,当a, b指针的某一个走到链列的末端时,将其指向对手链列(e.g. a->headB), 在推进一边,就可以有效解决长度不同的问题了。在第二遍遍历时,a和b要么相撞也就是重叠,要么同时走到末端。

# 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 not headA or not headB:
            return None

        a, b = headA, headB

        while a is not b:
            # if either pointer hits the end, switch head and continue the second traversal, 
            # if not hit the end, just move on to next
            a = headB if a is None else a.next
            b = headA if b is None else b.next

        return a 

你可能感兴趣的:(Intersection of Two Linked Lists两链列的交叉)