Solution 7: Determine if two linked lists Intersect

Source: Internet
Author: User

Problem description

Rt.

Solution Ideas

(1) Both lists are unidirectional linked lists: Determine whether the end nodes of the two lists are the same;

(2) One Ring in two lists, one without ring: impossible to intersect;

(3) Two linked lists have a ring: Slow-fast double pointer method.

Program

public class Listintersection {//Listpublic Boolean isintersectionoftwosinglelist (ListNode L1, ListNode L2) {i F (L1 = = NULL | | l2 = = NULL) {return false;} Whether the end of the list is Samelistnode endOfList1 = getendoflist (L1); ListNode endOfList2 = getendoflist (L2); return endOfList1 = = EndOfList2;} Private ListNode Getendoflist (ListNode head) {if (head = = null) {return null;} ListNode node = head;while (Node.next! = null) {node = Node.next;} return node;} Both list with Cyclepublic Boolean isintersectionoftwolistwithcycle (ListNode L1, ListNode L2) {if (L1 = null | | l2 = = N ULL) {return false;} ListNode slow = L1, fast = L2;while (Fast.next! = NULL | | Fast! = NULL | | Slow! = NULL) {slow = Slow.next;fast = Fast.next . next;if (slow = = fast) {return true;}} return false;}}

Solution 7: Determine if two linked lists Intersect

Related Article

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.