原题
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.
Credits:
Special thanks to @stellari for adding this problem and creating all test cases.
Reference Answer
思路分析
第一次遍历时,如果两者的非公共元素的个数正好相等,那么一定能找到相同元素;如果非公共元素个数不等,那么在一次遍历之后,两者的指针的差距就是非公共元素的个数差。这样翻转之后,指针的差距正好弥补了非公共元素的差,这样,第二次遍历要么一定相遇,要么两者没有公共元素,返回None。
这道题开始时候自己想麻烦了,想着先用判定是否有环程序进行判定是否有环;若无环,接着将两链表连接起来,找环的起始点做法找起始相交点,思路没错,不过太复杂了。
Code
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
lenA = lenB = 0
l1 = headA
l2 = headB
while l1:
lenA += 1
l1 = l1.next
while l2:
lenB += 1
l2 = l2.next
if lenA > lenB:
for _ in range(lenA - lenB):
headA = headA.next
else:
for _ in range(lenB - lenA):
headB = headB.next
while headA and headB and headA != headB:
headA = headA.next
headB = headB.next
return headA
# def judugeCircle(self, headA, headB):
# slow = headA
# fast = headA.next
# while fast and fast.next:
# if slow == fast:
# return True
# else:
# slow = slow.next
# fast = fast.next.next
# return False
# def findIntersection(self, headA, headB):
# head = headA
# while head and head.next:
# head = head.next
# head.next = headB
# slow = fast = head
# while fast and fast.next:
# if slow != fast:
# slow = slow.next
# fast = fast.next.next
# else:
# slow = head
# while slow != fast:
# slow = slow.next
# fast = fast.next
Note:
- 这道题重在思路,先去掉两链表长度的差值,这样,两者共同进行遍历,遍历到相同节点即为相交点。
参考资料
[1] https://blog.csdn.net/fuxuemingzhu/article/details/84640318