160. Intersection of Two Linked Lists

easy https://leetcode.com/problems/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:

160. Intersection of Two Linked Lists

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.

 

方法一:分别遍历 A 和 B 链表得到长度,较长的那个先走长度差值的 node 数,然后 A、B 一起走,看是否有相遇

 1 # Definition for singly-linked list.
 2 # class ListNode(object):
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.next = None
 6 
 7 class Solution(object):
 8     def getIntersectionNode(self, headA, headB):
 9         """
10         :type head1, head1: ListNode
11         :rtype: ListNode
12         """
13         if not headA or not headB:
14             return None
15         lenA, lenB = 0,0
16         temp = headA
17         while temp:
18             temp = temp.next
19             lenA += 1
20         temp = headB
21         while temp:
22             temp = temp.next
23             lenB += 1
24         if lenA>=lenB:
25             for i in range(lenA-lenB):
26                 headA = headA.next
27         else:
28             for i in range(lenB-lenA):
29                 headB = headB.next
30         while headA and headB:
31             if headA==headB:
32                 return headA
33             headA = headA.next
34             headB = headB.next
35         return None

 

方法二:利用题目中的链表无环的属性,A、B 同时从头出发,走到末尾处就转入对方的头节点,这样相遇的时候必然是走了相同的长度。若在尾部相遇则没有交叉节点,此时 A 和 B 均走了 len(A)+len(b) 的长度。若在中间相遇则相遇位置为交叉节点,此时 A 和 B 均走了 uniqueA+uniqueB+mutualAB 的长度。

 1 class Solution(object):
 2     def getIntersectionNode(self, headA, headB):
 3         """
 4         :type head1, head1: ListNode
 5         :rtype: ListNode
 6         """
 7         if not headA or not headB:
 8             return None
 9         a,b = headA,headB
10         while a!=b:
11             if a:
12                 a = a.next
13             else:
14                 a = headB
15             if b:
16                 b = b.next
17             else:
18                 b = headA
19         return a

 

上一篇:160. 相交链表


下一篇:LeetCodeWeeklyContest-160