160. Intersection of Two Linked Lists

easy https://leetcode.com/problems/intersection-of-two-linked-lists/node

題目描述:
Write a program to find the node at which the intersection of two singly linked lists begins.spa

For example, the following two linked lists:code

begin to intersect at node c1.blog

Notes:leetcode

  • 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 一塊兒走,看是否有相遇get

 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 的長度。it

 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
相關文章
相關標籤/搜索