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:

A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3

begin to intersect at node c1.

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.

   

来自 <https://leetcode.com/problems/intersection-of-two-linked-lists/description/>

1.思路:先上一个个人很蠢的实现,主要想法就是先获得短的链表长度,然后将长的链表往后面遍历,直到与短的链表一样长,之后两个链表同时往后遍历并进行对比,如果对比出现相同的,就返回该节点

class Solution(object):
    def getIntersectionNode(self, headA, headB):
        """
        :type head1, head1: ListNode
        :rtype: ListNode
        """
        p = headA
        len_a = 0
        while p != None:
            len_a += 1
            p = p.next
        p = headB
        len_b = 0
        while p != None:
            len_b += 1
            p = p.next
        if len_a==0 or len_b==0:
            return None
        if len_a > len_b:
            p = headA
            q = headB
        else:
            p = headB
            q = headA
        sub = abs(len_a - len_b)
        while sub:
            sub -= 1
            p = p.next
        node = p
        while p!=q:
            p = p.next
            q = q.next
            node = p
        return node
 

2.思路:常见的做法都是要获得两个链表的长度,有人提出来可以不用显示地计算长度,方法是先遍历两个列表,达到null时,就将其指向另一个列表头,这样就可以保证在第一次循环使得两个对象位于两个链表相同位置处,第二次循环地目标则是找出交点

 1 class Solution(object):
 2     def getIntersectionNode(self, headA, headB):
 3         """
 4         :type head1, head1: ListNode
 5         :rtype: ListNode
 6         """
 7         p = headA
 8         q = headB
 9         while p != q:
10             if p == None:
11                 p = headB
12             else:
13                 p = p.next
14             if q == None:
15                 q = headA
16             else:
17                 q = q.next
18         return p
原文地址:https://www.cnblogs.com/Thinker-pcw/p/9483976.html