【题目】
在本题中,单链表可能有环,也可能没环。给定两个单链表的头节点head1和head2,这两个单链表可能相交,也可能不相交。请实现一个函数,如果两个链表相交,请返回相交的第一个节点;如果不相交,返回null即可。
要求,时间复杂度O(N+M),空间复杂度O(1)。
【基本思路】
该问题可以分解成三个子问题:
问题一:如何判断一个链表是否有环,如果有的话返回第一个进环的节点,否则返回None。
问题二:如何判断两个无环链表是否相交,相交则返回第一个相交节点,否则返回None。
问题三:如何判断两个有环链表是否相交,相交则返回第一个相交节点,否则返回None。
另外,如果一个链表有环,一个链表无环,那么这两个链表是不可能相交的,直接返回None。
下面逐个解决三个子问题:
问题一:
使用两个指针slow和fast,slow一次走一步,fast一次走两步。如果无环,fast一定会走到None节点;否则,slow和fast一定会相遇,此时让fast回到头节点,接下来fast改为每次走一步,slow也是一次走一步,两个节点再次相遇的时候就是第一个入环节点。
证明如下:
具体实现参见如下代码:
#python3.5
def getLoopNode(head):
if head == None or head.next == None or head.next.next == None:
return None
slow = head.next
fast = head.next.next
while slow != fast:
if fast.next == None or fast.next.next == None:
return None
slow = slow.next
fast = fast.next.next
fast = head
while slow != fast:
slow = slow.next
fast = fast.next
return slow
问题二:
如果两个无环链表相交,那么从相交开始到结尾的这一段,是两个链表共享的。假设链表长度较长的链表为head1,长度为len1,链表长度较短的链表为head2,长度为len2。先让head1走len1 - len2步,然后开始同步走,第一次相遇的位置就是第一个相交节点。如果一直走到None也不相遇,则两链表不相交。具体实现如下:
def noLoop(head1, head2):
if head1 == None or head2 == None:
return None
cur1 = head1
cur2 = head2
n = 0
while cur1.next != None:
n += 1
cur1 = cur1.next
while cur2.next != None :
n -= 1
cur2 = cur2.next
if cur1 != cur2:
return None
cur1 = head1 if n >= 0 else head2
cur2 = head1 if cur1 == head2 else head2
n = abs(n)
while n != 0:
cur1 = cur1.next
n -= 1
while cur1 != cur2:
cur1 = cur1.next
cur2 = cur2.next
return cur1
问题三:
考虑问题三的时候,我们已经得到了两个链表各自的第一入环节点node1和node2。
如果两个有环链表相交,并且在入环之前就相交的话,即node1 == node2,该情况的求解和问题二类似,只不过终止的条件不再是遍历到None而是node1。
如果node1 != node2,那么从node1开始遍历,如果node2和node1在同一个环中,node1遍历一圈一定会与node2相遇,此时返回node1和node2都可以;如果没有相遇,则两个链表不相交,返回None。
具体实现如下:
def bothLoop(head1, node1, head2, node2):
if head1 == None or head2 == None:
return None
if node1 == node2:
cur1 = head1
cur2 = head2
n = 0
while cur1 != node1:
n += 1
cur1 = cur1.next
while cur2 != node1:
n -= 1
cur2 = cur2.next
cur1 = head1 if n >= 0 else head2
cur2 = head1 if cur1 == head2 else head2
n = abs(n)
while n != 0:
n -= 1
cur1 = cur1.next
while cur1 != cur2:
cur1 = cur1.next
cur2 = cur2.next
return cur1
else:
cur1 = node1.next
while cur1 != node1:
if cur1 == node2:
return node1
cur1 = cur1.next
return None
主函数实现如下:
class Node:
def __init__(self, val=None):
self.val = val
self.next = None
def getIntersectNode(head1, head2):
if head1 == None or head2 == None:
return None
node1 = getLoopNode(head1)
node2 = getLoopNode(head2)
if node1 == None and node2 == None:
return noLoop(head1, head2)
if node1 != None and node2 != None:
return bothNode(head1, node1, head2, node2)
return None