题目:
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.
题意:
写一个函数找两个单链表交集的起始位置。
代码:
# 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 headA == None or headB == None :
return None
else :
nodeA = headA #指针1
nodeB = headB #指针2
while nodeA != None and nodeB != None: #遍历A和B,直到短的链表遍历结束
nodeA = nodeA.next
nodeB = nodeB.next
if nodeA == None : #如果A短,则指针1指向B,直到遍历B结束,找到B-A的差值
nodeA = headB
while nodeA != None and nodeB != None:
nodeA = nodeA.next
nodeB = nodeB.next
nodeB = headA #同时指针2指向A,两个指针开始同步比较
else :
if nodeB == None : #如果B短,则进行相应的操作
nodeB = headA
while nodeA != None and nodeB != None:
nodeA = nodeA.next
nodeB = nodeB.next
nodeA = headB
while nodeA and nodeA.val != nodeB.val : #两个链表找到从后开始的相同长度的起始位置后,就开始比较,找出公共部分的起点
nodeA = nodeA.next
nodeB = nodeB.next
return nodeA
笔记:
本题用python写的代码,但是并不能AC,因为总是会报:
Submission Result: Memory Limit Exceeded
用C++写的代码,就能AC
思路:
其实大家思路都差不多,都是计算单链表A和B的长度,然后用长的减去短的,得到差值后,长的单链表先走,经过计算得到的差值的节点后,两个单链表开始比较,寻找交集的起始节点。