问题描述:
编写一个程序,找到两个单链表相交的起始节点。
例如,下面的两个链表:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3
在节点 c1 开始相交。
方法1:
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 p = headA 10 q = headB 11 while p and q: 12 if p.val == q.val: 13 14 return p 15 elif p.val < q.val: 16 p = p.next 17 else: 18 q = q.next 19 return None
官方:求出两个表的长度,表长的先走一个差值。
1 class Solution(object): 2 def getIntersectionNode(self, headA, headB): 3 """ 4 :type head1, head1: ListNode 5 :rtype: ListNode 6 """ 7 lenA = 0 8 headA_c1 = headA 9 while headA_c1: 10 lenA += 1 11 headA_c1 = headA_c1.next 12 lenB = 0 13 headB_c1 = headB 14 while headB_c1: 15 lenB += 1 16 headB_c1 = headB_c1.next 17 headA_c2 = headA 18 headB_c2 = headB 19 if lenA > lenB: 20 for i in range(lenA-lenB): 21 headA_c2 = headA_c2.next 22 elif lenA < lenB: 23 for i in range(lenB-lenA): 24 headB_c2 = headB_c2.next 25 while headA_c2 and headB_c2: 26 if headA_c2 == headB_c2: 27 return headA_c2 28 headB_c2 = headB_c2.next 29 headA_c2 = headA_c2.next 30 return None
方法3:
1 class Solution(object): 2 def getIntersectionNode(self, headA, headB): 3 """ 4 :type head1, head1: ListNode 5 :rtype: ListNode 6 """ 7 temp = set() 8 tempA = headA 9 tempB = headB 10 11 if headA and headB is None: 12 return None 13 14 while tempA: 15 temp.add(tempA) 16 tempA = tempA.next 17 18 while tempB: 19 if tempB in temp: 20 return tempB 21 tempB = tempB.next 22 23 return None
2018-09-14 16:26:48