[leetcode]#160. Intersection of Two Linked Lists

来源:互联网 发布:任务管理 知乎 编辑:程序博客网 时间:2024/05/28 06:07
  • 题目:写一个程序,找到两个单链表交汇的节点。比如,下面两个单链表交汇节点是c1:

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

注意:1,如果两个单链表不交,返回null;2,函数返回后,两个单链表的原始顺序不能改变;3,假定整个结构中没有环;4,你的程序最好以时间复杂度O(n),空间复杂O(1)运行。

  • 可以不用计算两个链表的长度,因为本质上我们关心的是让两个链表的指针同时到达交叉点。我们可以定义两个指针,让它们都将两个链表都遍历一遍,那么它们走的总长度是一样的,倘若两个链表相交,那么这两个指针一定会在某个地方相等。
# Definition for singly-linked list.# class ListNode(object):#     def __init__(self, x):#         self.val = x#         self.next = Noneclass Solution(object):    def getIntersectionNode(self, headA, headB):        """        :type head1, head1: ListNode        :rtype: ListNode        """        if not headA or not headB:            return None        p, q = headA, headB        while p and q and p != q:            p = p.next            q = q.next            if p == q:                return p            if not p:                p = headB            if not q:                q = headA        return p