当前位置:   article > 正文

java+链表+相交_java判断两个单链表是否相交

java判断链表是否相交

思路:

链表分有环链表和无环链表,如果两个链表存在相交,则只有两种可能,两个链表都无环或者都有环。

(1)如果链表都无环,则先判断链表的尾指针是否一样,如果不一样,则没有相交。如果一样,则找出两个链表的长度差,将两个链表从距离尾节点同样的距离进行扫描,如果相交,则必然有一处扫描节点相同。实例数据List1:1->2->3->4->5->6->7->null,List2:0->9->8->6->7->null,第一个相交节点为6

示例图如下,

06fad95ad6cc2d60ae4582fe1f44b3a2.png

(2)如果链表都有环,则只肯能有下面两种情况(如下图)。两种情况区分的方法为:入环点是否相同。

如果相同则为第一种情况:那么查找第一个相交点与无环的单链表相交找第一个交点的方法一样。

如果入环点不同,则为第二种情况,这个相交点或者为list1 的入环点loop1或者为list2的入环点loop2。

情况1实例数据(List1:1->2->3->4->5->6->7->4,List2:0->9->8->2->3->4->5->6->7->4,第一个交点为2)

情况2实例数据(List1:1->2->3->4->5->6->7->4,List2:0->9->8->6->7->4->5->6,第一个交点为4或6)

e931d046eb38ec281378bbf6357a42fc.png            

1362e931cb68b0e349668bf3d7afa6eb.png

public static classNode {public intvalue;publicNode next;public Node(intdata) {this.value =data;

}

}/*判断是否相交,如果相交,得到第一个相交点*/

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

}

Node loop1=getLoopNode(head1);

Node loop2=getLoopNode(head2);if (loop1 == null && loop2 == null) {returnnoLoop(head1, head2);

}if (loop1 != null && loop2 != null) {returnbothLoop(head1, loop1, head2, loop2);

}return null;

}/** 判断是否存在环,如果存在,则找出环的入口点。

* 入口点找法:快慢指针,块指针走两步,满指针走一步,如果存在循环,则在慢指针走完环前,总会和快指针相遇。

* 从头指针和相遇点同时向后走,相遇的点必定是入口点。*/

public staticNode getLoopNode(Node head) {if (head == null || head.next == null || head.next.next == null) {return null;

}

Node n1= head.next; //n1 -> slow

Node n2 = head.next.next; //n2 -> fast

while (n1 !=n2) {if (n2.next == null || n2.next.next == null) {return null;

}

n2=n2.next.next;

n1=n1.next;

}

n2= head; //n2 -> walk again from head

while (n1 !=n2) {

n1=n1.next;

n2=n2.next;

}returnn1;

}/*无环时的判断方法*/

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

}

Node cur1=head1;

Node 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;

}

cur1= n > 0 ?head1 : head2;

cur2= cur1 == head1 ?head2 : head1;

n=Math.abs(n);while (n != 0) {

n--;

cur1=cur1.next;

}while (cur1 !=cur2) {

cur1=cur1.next;

cur2=cur2.next;

}returncur1;

}/*有环时的判断方法*/[java] view plain copypublic staticNode bothLoop(Node head1, Node loop1, Node head2, Node loop2) {

Node cur1= null;

Node cur2= null;if (loop1 ==loop2) {

cur1=head1;

cur2=head2;int n = 0;while (cur1 !=loop1) {

n++;

cur1=cur1.next;

}while (cur2 !=loop2) {

n--;

cur2=cur2.next;

}

cur1= n > 0 ?head1 : head2;

cur2= cur1 == head1 ?head2 : head1;

n=Math.abs(n);while (n != 0) {

n--;

cur1=cur1.next;

}while (cur1 !=cur2) {

cur1=cur1.next;

cur2=cur2.next;

}returncur1;

}else{

cur1=loop1.next;while (cur1 !=loop1) {if (cur1 ==loop2) {returnloop1;

}

cur1=cur1.next;

}return null;

}

}

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/689885
推荐阅读
相关标签
  

闽ICP备14008679号