首页 > 其他 > 详细

160. 相交链表

时间:2020-05-09 14:52:22      阅读:46      评论:0      收藏:0      [点我收藏+]

技术分享图片
技术分享图片
技术分享图片
技术分享图片
技术分享图片
技术分享图片


方法一:

指针a,b分别从headA和headB遍历,到尾后,b再从headA遍历,a从headB遍历;

当a==b时记录下此节点ans,若此后到尾一直相等则返回ans。

交叉遍历,可以保证不论两个链表哪个长,指针遍历的节点数一样多。

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

方法二:

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

160. 相交链表

原文:https://www.cnblogs.com/panweiwei/p/12857170.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!