Linked List Intersection
The head pointers of two one-way linked lists, such as h1 and h2, are given to determine whether the two linked lists are intersecting.
Solution:
1. first determine whether the linked list has a ring
2. If there is no ring, both linked lists traverse to the last node to determine whether the nodes are the same.
3. A ring must be intersecting.
[Cpp]
Struct Node {
Int data;
Int Node * next;
};
// If there is no cycle.
Int isJoinedSimple (Node * h1, Node * h2 ){
While (h1-> next! = NULL ){
H1 = h1-> next;
}
While (h2-> next! = NULL ){
H2 = h2-> next;
}
Return h1 = h2;
}
// If there cocould exist cycle
Int isJoined (Node * h1, Node * h2 ){
Node * cylic1 = testCylic (h1 );
Node * cylic2 = testCylic (h2 );
If (cylic1 + cylic2 = 0) return isJoinedSimple (h1, h2 );
If (cylic1 = 0 & cylic2! = 0 | cylic1! = 0 & cylic2 = 0) return 0;
Node * p = cylic1;
While (1 ){
If (p = cylic2 | p-> next = cylic2) return 1;
P = p-> next;
Cylic1 = cylic1-> next;
If (p = cylic1) return 0;
}
}
Node * testCylic (Node * h1 ){
Node * p1 = h1, * p2 = h1;
While (p2! = NULL & p2-> next! = NULL ){
P1 = p1-> next;
P2 = p2-> next;
If (p1 = p2 ){
Return p1;
}
}
Return NULL;
}
Struct Node {
Int data;
Int Node * next;
};
// If there is no cycle.
Int isJoinedSimple (Node * h1, Node * h2 ){
While (h1-> next! = NULL ){
H1 = h1-> next;
}
While (h2-> next! = NULL ){
H2 = h2-> next;
}
Return h1 = h2;
}
// If there cocould exist cycle
Int isJoined (Node * h1, Node * h2 ){
Node * cylic1 = testCylic (h1 );
Node * cylic2 = testCylic (h2 );
If (cylic1 + cylic2 = 0) return isJoinedSimple (h1, h2 );
If (cylic1 = 0 & cylic2! = 0 | cylic1! = 0 & cylic2 = 0) return 0;
Node * p = cylic1;
While (1 ){
If (p = cylic2 | p-> next = cylic2) return 1;
P = p-> next;
Cylic1 = cylic1-> next;
If (p = cylic1) return 0;
}
}
Node * testCylic (Node * h1 ){
Node * p1 = h1, * p2 = h1;
While (p2! = NULL & p2-> next! = NULL ){
P1 = p1-> next;
P2 = p2-> next;
If (p1 = p2 ){
Return p1;
}
}
Return NULL;
} The first common node of a linked list that does not have a ring to calculate an intersection list
Solution:
Method 1: Use two cycles
Method 2: Mark the accessed Node
Method 3: Use the difference between the number of nodes A and B
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.