public class IsListsIntersection {
public static boolean isListsInters(Node h1, Node h2){
if (h1 == null || h2 == null){
return false;
}
while (h1.getNext() != null){
h1 = h1.getNext();
}
while (h2.getNext() != null){
h2 = h2.getNext();
}
return h1 == h2;
}
public static void main(String[] args){
Node h1 = new Node(1);
Node n2 = new Node(2);
Node h2 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
h1.setNext(n2);
n2.setNext(n4);
h2.setNext(n4);
n4.setNext(n5);
System.out.println("h1与h2相交:"+IsListsIntersection.isListsInters(h1,h2));
}
}
public static Node getFirstIntersList(Node h1, Node h2){
int distance = Node.getLength(h1) - Node.getLength(h2);
if (distance > 0){
h1 = IsListsIntersection.movePosD(h1,distance);
}else{
h2 = IsListsIntersection.movePosD(h2,distance);
}
while ( h1 != null && h2 != null){
if (h1 == h2){
return h1;
}
h1 = h1.getNext();
h2 = h2.getNext();
}
return null;
}
public static Node movePosD(Node h, int dis){
while (h != null && dis >0){
h = h.getNext();
dis--;
}
return h;
}
public static void printList(Node h){
while (h != null){
System.out.print(h.getData()+" ");
h = h.getNext();
}
}
public static void main(String[] args){
Node h1 = new Node(1);
Node n2 = new Node(2);
Node h2 = new Node(3);
Node n4 = new Node(4);
Node n5 = new Node(5);
h1.setNext(n2);
n2.setNext(n4);
h2.setNext(n4);
n4.setNext(n5);
Node commonList = IsListsIntersection.getFirstIntersList(h1,h2);
IsListsIntersection.printList(commonList);
}
评论