public Node mergeList(Node head1, Node head2) {
if (head1 == null || head2 == null) {
System.out.println("没有公共节点");
return null;
}
Node longNode;
Node shortNode;
int gapCount = 0;
int head1Length = getLength(head1);
int head2Length = getLength(head2);
if (head1Length > head2Length) {
longNode = head1;
shortNode = head2;
gapCount = head1Length - head2Length;
} else {
longNode = head2;
shortNode = head1;
gapCount = head2Length - head1Length;
}
for (int i = 0; i <gapCount; i++) {
longNode = longNode.next;
}
while (longNode != null && shortNode != null && longNode != shortNode) {
System.out.println("long---"+longNode.data);
System.out.println("short----"+shortNode.data);
longNode = longNode.next;
shortNode = shortNode.next;
if(longNode.data==shortNode.data){
head=longNode;
System.out.println("第一个公共节点是"+head.data);
return head;
}
}
return longNode;
}
评论