java-finding the first common node of two single-linked lists

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.