logologo

两个链表都无环,返回第一个相交节点,如果不相交,返回 NULL

Sep 5, 2023

两个链表都无环,返回第一个相交节点,如果不相交,返回 NULL

链表

public Node noLoop(Node head1, Node head2) {
  if (head1 == null || head2 == null)
    return null;

  Node cur1 = head1, cur2 = head2;
  int n = 0;
  while (cur1.next != null) {
    n++;
    cur1 = cur1.next;
  }

  while (cur2.next != null) {
    n--;
    cur2 = cur2.next;
  }

  if (cur1 != cur2)
    return null;

  // n=|head1.size - head2.size|
  cur1 = n > 0 ? head1 : head2;// who is long, who is cur1.
  cur2 = cur1 == head1 ? head2 : head1;// who is short, who is cur2.

  n = Math.abs(n);
  while (n != 0) {
    n--;
    cur1 = cur1.next;
  }
  while (cur1 != cur2) {
    cur1 = cur1.next;
    cur2 = cur2.next;
  }
  return cur1; // 此时返回的是第一个相交节点
}

C++Java
浙ICP备2021022773号    2022-PRESENT © ZhengKe