题目
解法
class Node {
// 指针
Node next;
// 数据
int data;
public Node(int data) {
this.data = data;
}
}
/**
* 查询第一个公共节点
*
* @param nodeOne
* @param nodeTwo
* @return
*/
public Node findFirstCommonNodeTwo(Node nodeOne, Node nodeTwo) {
if (nodeOne == null || nodeTwo == null) return null;
Node first = nodeOne;
Node second = nodeTwo;
while (first != second) {
first = (first == null ? second : first.next);
second = (second == null ? first : second.next);
}
return first;
}
/**
* 查找两个链表的第一个公共节点
*
* @param headOne
* @param headTwo
* @return
*/
public Node findFirstCommonNode(Node headOne, Node headTwo) {
int nodeOneLength = getLength(headOne);
int nodeTwoLength = getLength(headTwo);
// 长链表头节点
Node nodeLong = headOne;
// 短链表头结点
Node nodeShort = headTwo;
// 对比长度
int diffLength;
if (nodeOneLength > nodeTwoLength) {
diffLength = nodeOneLength - nodeTwoLength;
} else {
nodeLong = headTwo;
nodeShort = headOne;
diffLength = nodeTwoLength - nodeOneLength;
}
// 移动头指针
for (int i = 0; i < diffLength; i++) {
nodeLong = nodeLong.next;
}
// 遍历比对
while (nodeLong != null && nodeShort != null && nodeLong != nodeShort) {
nodeLong = nodeLong.next;
nodeShort = nodeShort.next;
}
return nodeLong;
}