Title: Enter the two lists to find their first common node.
def first_common_node(head1,head2): p1,p2 = head1,head2 cnt1,cnt2=0,0 while p1: cnt1 +=1 p1=p1.next while p2: cnt2 +=1 p2=p2.next p1, p2 = head1, head2 if cnt1>cnt2: for i in range(cnt1-cnt2): p1=p1.next if cnt2>cnt1: for i in range(cnt2-cnt1): p2=p2.next while p1.data!=p2.data: p1=p1.next p2=p2.next return p1
Note: To find out the first two lists common node, as long as two lists in the same length after each one node and then traversed back together, when faced with two nodes are the same, namely a first common node . First, it calculates the length of two lists, and then let go the long list, so that the remaining length of the list is equal to another, and can be traversed together.
The second method is a two stack storage two lists, and then do the two stack pop operation, it is determined whether the two nodes same stack pop, the last one and the same node is a common node of the first two lists.