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.
分析:
如果两个链表等长的话,那么我们只需依次遍历比较这两个链表的节点是否相同即可,所以如果不等长的话,我们将长的链表多出的节点先遍历过,然后再比较即可。这样只需要计算每个链表的长度,时间复杂度为O(N),空间复杂度为O(1)。代码如下:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
# @param two ListNodes
# @return the intersected ListNode
def getIntersectionNode(self, headA, headB):
curA,curB = headA,headB
lenA,lenB = 0,0
while curA is not None:
lenA += 1
curA = curA.next
while curB is not None:
lenB += 1
curB = curB.next
curA,curB = headA,headB
if lenA > lenB:
for i in range(lenA-lenB):
curA = curA.next
elif lenB > lenA:
for i in range(lenB-lenA):
curB = curB.next
while curB != curA:
curB = curB.next
curA = curA.next
return curA