[leetcode]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:

begin to intersect at node c1.

分析

这个题目目的是找到两个单链表的交叉点,如果没有交叉点那么返回null
一般思路是遍历两个单链表一个个对比,但是这样复杂度非常高。讨巧的方法类似于第141题, 把两个单链表想象成环。


A 指针从 链表 headA 开始遍历,当到达最后一个节点时,再把A指向HeadB;
B 指针从 链表 headB 开始遍历,当到达最后一个节点时,再把B指向HeadA;
这样,对于不同长度的两个链表,假如他们是相交的,总能找到交点使得A == B。

再看不相交的情况。


当链表长度不同时,且A 和 B的下一个节点同时为空时,说明两个链表已经分别被A,B指针遍历过一次,至此还没有交点,说明两者不相交。

代码

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        a = headA
        b = headB
        while(a or b):
            if a == b :
                return a
            if not a:
                a = headB
            else:
                a = a.next
                
            if not b:
                b = headA
            else:
                b = b.next        
        return None

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