zoukankan      html  css  js  c++  java
  • 160. 相交链表







    方法一:

    指针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
    
  • 相关阅读:
    SpringBoot笔记
    SpringBoot面试篇
    多线程篇
    Tomcat篇
    Redis篇
    Nginx篇
    JVM篇
    MySQL篇
    python ETL工具 pyetl
    python通用数据库操作工具 pydbclib
  • 原文地址:https://www.cnblogs.com/panweiwei/p/12857170.html
Copyright © 2011-2022 走看看