写程序找寻两个单链表开始相交的起点
For example, the following two linked lists:
A: a1 → a2 ↘ c1 → c2 → c3 ↗ B: b1 → b2 → b3begin to intersect at node c1.
注意:
如果两个链表不相交就返回Null
函数返回之后两个单链表必须保持原始状态不变
假设整个单链表结构中没有环
代码运行时间最好是O(n),额外申请的内存最好为O(1)
1:将两个链表分别转换为两个列表,从列表的尾部开始对比两个列表的节点是否相等,并进行相应操作,时间复杂度O(n),额外申请空间O(n)
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
aList = []
bList = []
tempA = headA
tempB = headB
while tempA is not None: #链表A转列表
aList.append(tempA)
tempA = tempA.next
while tempB is not None: #链表B转列表
bList.append(tempB)
tempB = tempB.next
while len(aList)>1 and len(bList)>1 and aList[-2]==bList[-2]: #判断条件,一旦不满足条件就退出循环
aList.pop()
bList.pop()
if aList[-1]==bList[-1]: #如果此时两个列表的最后一个元素相等,就说明有交汇,且该节点即为交叉开始的节点
return bList[-1]
else:
return None
2:双指针法,时间复杂度O(n),额外未申请空间(参考他人代码)
#双指针法,制定两个指针pA pB,分别用这两个指针遍历A+B,如果两个指针在某点相遇,则该点就是链表的交点
#A=[1,3,5,7,9,11]
#B=[2,4,6,8,9,11]
#A+B的链表长度是一定的,如果有交点,那么这个长链表从后向前看的前几个必定是相同的
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
if not headA or not headB:
return None
tempA = headA
tempB = headB
while tempA!=tempB:
tempA = tempA.next
tempB = tempB.next
if not tempA and not tempB:
return None
if not tempA: #A链表后面接上B链表
tempA = headB
if not tempB: #B链表后面接上A链表
tempB = headA
return tempA
3:将headA变为字典,然后判断headB中节点是否在字典中存在,返回相应的结果(参考他人代码)
def getIntersectionNode(self, headA, headB):
"""
:type head1, head1: ListNode
:rtype: ListNode
"""
cpmDic = {}
while headA is not None:
cpmDic[headA] = 1
headA = headA.next
while headB is not None:
if cpmDic.has_key(headB):
return headB
headB = headB.next
return None
算法题来自:https://leetcode-cn.com/problems/intersection-of-two-linked-lists/description/