Simple algorithm in single-linked list
/** * Get two single-linked list of common nodes * first to find out the length of the two linked lists, and find the difference between the two dif, two pointers to the list head, respectively, so that the pointer to the long list of links to the end of the list to move the dif step. * Last step to move two pointers together, when two pointers point to the same node, return that node * @param list1 * @param list2 * @return */public static ListNode Getfirstcommonnode ( ListNode List1,listnode List2) {if (List1==null | | list2==null) {return null;} int length1 = Getlistlength (list1); int length2 = Getlistlength (List2); ListNode longlist = List2; ListNode shortList = List1;int dif = length2-length1;if (length1 > length2) {longlist = List1;shortlist = List2;dif = L Ength1-length2;} while (dif>0) {longlist = Longlist.getnext ();d if--;} while (longlist!=null && shortlist!=null && longlist!=shortlist) {longlist = Longlist.getnext (); ShortList = Shortlist.getnext ();} return longlist;} /** * Get the length of the linked list * @param list * @return */public static int getlistlength (ListNode list) {int length = 0;while (list! = null) { Length++;list = List.getnext ();} return length;}
Java-find the first common node of two single-linked lists