zoukankan      html  css  js  c++  java
  • 160. Intersection of Two Linked Lists

     

    Description:

    Write a program to find the node at which the intersection of two singly linked lists begins.
    

    求两链表的交集

    Examples:

    A:          a1 → a2
                       ↘
                         c1 → c2 → c3
                       ↗            
    B:     b1 → b2 → b3

    notes:
    • If the two linked lists have no intersection at all, return null.
    • The linked lists must retain their original structure after the function returns.
    • You may assume there are no cycles anywhere in the entire linked structure.
    • Your code should preferably run in O(n) time and use only O(1) memory.

    Solution:

    class Solution:
        # @param two ListNodes
        # @return the intersected ListNode
        def getIntersectionNode(self, headA, headB):
            if headA is None or headB is None:
                return None
    
            pa = headA # 2 pointers
            pb = headB
    
            while pa is not pb:
                # if either pointer hits the end, switch head and continue the second traversal, 
                # if not hit the end, just move on to next
                pa = headB if pa is None else pa.next
                pb = headA if pb is None else pb.next
    
            return pa # only 2 ways to get out of the loop, they meet or the both hit the end=None
    

      

  • 相关阅读:
    lftp使用普通ftp模式登录
    echo 单引号和双引号
    断言、检查点相关函数方法
    hierarchyviewer
    Uiautomatorviewer
    Appium Inspector
    Python+requests+unittest+excel实现接口自动化测试框架
    Selenium IDE
    面试总结
    常见问题总结
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9162266.html
Copyright © 2011-2022 走看看