简体   繁体   中英

Intersection Point of Two Lists JAVA

Question : Given head nodes of two linked lists that may or may not intersect, find out if they intersect and return the point of intersection; return null otherwise.

Solution time:o(m+n),space o(1) :

  • Find lengths of both linked lists: L1 and L2
  • Calculate difference in length of both linked lists: d = |L1 - L2|
  • Move head pointer of longer list 'd' steps forward
  • Now traverse both lists, comparing nodes until we find a match or reach the end of lists

在此处输入图片说明

Here's the code:

public static LinkedListNode intersect(
    LinkedListNode head1,
    LinkedListNode head2) {

    LinkedListNode list1node = null;
    int list1length = get_length(head1);
    LinkedListNode list2node = null;
    int list2length = get_length(head2);

    int length_difference = 0;
    if(list1length >= list2length) {
      length_difference = list1length - list2length;
      list1node = head1;
      list2node = head2;
    } else {
      length_difference = list2length - list1length;
      list1node = head2;
      list2node = head1;
    }

    while(length_difference > 0) {
      list1node = list1node.next;
      length_difference--;
    }

    while(list1node != null) {
      if(list1node == list2node) {
        return list1node;
      }

      list1node = list1node.next;
      list2node = list2node.next;
    }
    return null;
}

However , I'm thinking is there a possible that the Intersection Point just appear at the position before d steps in the longer list? Like: 在此处输入图片说明

I'm confused, please help me clear my mind, thank you!

A node can only has one successor. While in the second picture, the intersection node get two successors, which is impossible.

No. That is not possible. Because after the intersection point, the rest of both lists should be the same which means that they should have

  1. the same length after that point
  2. each element after that point is the same.

So it is not possible before d steps since that will not satisfy point 1.

Your algorithm is correct. However, after the intersection point, its no longer two lists, its just one list.

So whatever difference d you have in no. of nodes, it is before the intersection point.

First thing, you cannot create singly linked list with your given input. A node can point only to single next node. In your input, node points to two next nodes. You need to find the intersection point where the two lists converge. Your algorithm will find the intersection point immediately after 'd' nodes which is the expected output

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM