Two one-way lists to determine if they intersect, and if they intersect, find their first common node.

Source: Internet
Author: User

Ideas:

First, a fast and slow pointer is used to determine whether a chain list exists.

(1) If there is no ring, then if the two linked lists intersect with a common node, that is, from a node, their next point points to the same node. So we judge whether the two linked lists intersect, as long as the two linked lists are traversed to the end respectively. If the two end nodes are the same, they intersect; otherwise, two lists do not want to be handed in.

Link lists intersect, how to find the first intersection node. First, the two lists are traversed once, the length of the two lists is l1,l2, and then the length difference of the two linked list L is obtained. Then the long list is now traversed by the L nodes, and then synchronously traversed, so the first common node in the traversal process is the first one. The time complexity of this method is O (L1+L2).

(2) If one exists ring and the other does not exist, then the two lists are disjoint.

(3) If there is a ring, then judge any one of the list of fast and slow pointer encounters the node, on the other linked list. If in, then intersect, if not, then not intersect.

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.