Problem: If two single-chain table A and table B have an intersection, return the position of the first intersection in Table A (the node position in the head of the linked list is 0 ).
Analysis: if there is an intersection between A and B, the successor of the intersection must also be the intersection, so it must be Y-type intersection. Therefore, the idea of the algorithm is as follows:
1) obtain the length of a and B, such as alength and blength.
2) determine who is alength or blength, such as alength> blength
3) When alength is moved to the alength-blength location, it starts to judge whether each node is equal. If it is equal, it exits.
In this blog, "[Introduction to algorithms-20] Single-linked Table Implementation" is a single-linked table class. Java implementation:
/* Return the position of the node in the linked list. Note that the first node of the linked list is 0 */public static integer getpositionoffirstintersectionnode (singlylinkedlist <integer> A, singlylinkedlist <integer> B) {int lenghtofa =. getlength (); int lengthofb = B. getlength (); int counter =-1;/* Get the header pointer */node <integer> nodeofa =. getprehead (); node <integer> nodedofb = B. getprehead ();/* align two linked lists */If (lenghtofa! = Lengthofb) {While (lenghtofa> lengthofb) {nodeofa = nodeofa. getnext (); lenghtofa --; counter ++;} while (lenghtofa <lengthofb) {nodedofb = nodedofb. getnext (); lenghtofa --;}/* after alignment, determine whether each node is equal */while (nodeofa! = NULL & nodedofb! = NULL) {If (nodeofa. equals (nodedofb) {break;} else {nodeofa = nodeofa. getnext (); nodedofb = nodedofb. getnext (); counter ++;} return counter ;}
**************************************** **************************
Test:
Public static void main (string [] ARGs) {// todo automatically generated method stub singly1_list <integer> singly1_lista = new singly1_list <> (); singly1_list <integer> singly1_listb = new singly1_list <> (); node <integer> node1 = new node <integer> (-1 ); node <integer> node2 = new node <integer> (1); node <integer> node3 = new node <integer> (2 ); node <integer> node4 = new node <integer> (0); node <integer> node5 = new node <integer> (3 ); node <integer> node6 = new node <integer> (4); node <integer> node7 = new node <integer> (5); singly1_lista. add (node1); singly1_lista. add (node2); singly1_lista. add (node3); singly1_lista. add (node5); singly1_lista. add (node6); singly1_lista. add (node7); singly1_listb. add (node4); singly1_listb. add (node5); singly1_listb. add (node6); singly1_listb. add (node7); int positon = getpositionoffirstintersectionnode (singly1_lista, singly1_listb); system. out. println (positon );}
[Introduction to algorithms-23] intersection of two single-linked tables (single-linked)