Http://geeksforgeeks.org /? P = 2405
There are two one-way linked lists, A and B, as shown in. They converge on a node (15 in this example) and write a program to find the first intersection point:
Method 1: Use two cycles
Foreach nodea in lista
Foreach NodeB in listb
If NodeB = nodea
Then a and B intersect at the current node, I. e., nodea (or equivalently NodeB)
Assume that the length of linked list A is m and that of linked list B is n. The complexity of this algorithm is O (Mn), which is not ideal.
Method 2: Mark the accessed Node
First, add a flag bvisited to each node, indicating whether the node has been accessed. The initial value is false.
Then, in the traversal process of Table A, each node in Table A is marked as accessed (set bvisited = true). Then, in the traversal process, if a accessed node is found, the node is the intersection of A and B.
The complexity of this algorithm is O (m + n), which is better than method 1. However, this method needs to add a flag for each node. A work und is to use the hash table to record whether a node has been accessed.
Method 3: Use the difference between the number of nodes A and B
Observe the graph given at the beginning of this article. We can see that if two linked lists A and B intersect, they will present a Y-shaped, we can use the difference between the number of nodes A and B to determine where they are located. The steps are as follows:
1) calculate the number of nodes in the linked list A and record it as C1;
2) calculate the number of nodes in the Linked List B and record it as C2;
3) calculate the number of nodes: D = ABS (C1-C2 );
4) Now, we start from a list with a large number of nodes and walk forward from the first node to the second node. The two linked lists have the same number of nodes.
5) Now we can traverse two linked lists at the same time until we can find an intersection.
The complexity of this algorithm is O (m + n), which is recommended.