Title Description Enter two lists to find their first common node. When you see this problem, a lot of people's first reaction is to use brute force method: On the first linked list to traverse each node sequentially, each traversal to a node, on the second linked list sequentially traverse each node. If the node on the second list is the same as the node on the first list, it means that the two linked lists overlap on the nodes, and then the public nodes are found. And usually brute force is not a good way. Train of thought: The first case: the same length has the intersection of two pointers together walk, the step is consistent, hit the first same node P1 = = P1, exit the loop, return P1. Second case: The same length without the intersection of two pointers go together, until the last node, P1.next and P2.next are none, meet the equal conditions, exit the loop, return P1. The third case: a different length has the intersection of two pointers together, when a pointer P1 go to the end point, the P1 is located in the list is relatively short, let P1 point to another list of the head node to start walking, until P2 go to the end, so P2 point to the short list of the head node, then the next two pointers to go the same length Become the first case. Fourth case: Different lengths without intersection of two pointers together, when a pointer P1 go to the end point, the P1 is located in the list is relatively short, let P1 point to another list of the head node to start walking, until P2 to the end, so that P2 point to the short list of the head node, then the next two pointers to go the same length, becomes the second case.
1 #-*-coding:utf-8-*-2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 classSolution:7 defFindfirstcommonnode (self, PHead1, pHead2):8 #Write code here9 Ten if notPHead1or notpHead2: One returnNone AP1 =PHead1 -P2 =pHead2 - the whileP1! =P2: - if notP1: -P1 =pHead2 - Else: +P1 =P1.next - + if notP2: AP2 =PHead1 at Else: -P2 =P2.next - returnP1 - -
Reference: Http://blog.csdn.net/lynette_bb/article/details/https://www.baidu.com/link?url= R7xvatifwdwdfozy414lsw2g-bahk0uieeoocvzh-fshhkfpqphcy4dir8andhdodjejihiw-emlsaafcdxjfafn0ux2qamdzqrvhvtf9le &wd=&eqid=d66f34b40000306b000000065a93ae50
The first common node of a Python two list