private static LinkNode findFirstMergedNode(LinkNode a, LinkNode d) {
// compute length
int length1 = 0, length2 = 0;
LinkNode tempNode = a;
while (tempNode.next != null) {
length1++;
tempNode = tempNode.next;
}
tempNode = d;
while (tempNode.next != null) {
length2++;
tempNode = tempNode.next;
}
LinkNode tempa = a;
LinkNode tempd = d;
// skip nodes
int sub = length1 - length2;
if (sub > 0) {
for (int i = 0; i < sub; i++) {
tempa = tempa.next;
}
} else if (sub < 0) {
for (int i = sub; i < 0; i++) {
tempd = tempd.next;
}
}
// find the first merged node
while (tempa != tempd) {
tempa = tempa.next;
tempd = tempd.next;
}
return tempa;
}
评论