LinkedList:两个单链表,返回第一个相交点,假设2个单链
作者:
敲一手烂代码 | 来源:发表于
2016-05-18 13:43 被阅读0次public Node getIntersectionNode(Node headA, Node headB) {
if (headA==null||headB==null) {
return null;
}
Node node1 = headA;
Node node2 = headB;
int headACount = 0;
int headBCount = 0;
while (node1.next!=null) {
node1 = node1.next;
++headACount;
}
while (node2.next!=null) {
node2 = node2.next;
++headBCount;
}
if (node1!=node2) {
return null;
}
int step = headACount-headBCount;
if (step>0) {
while (step>0) {
headA = headA.next;
step--;
}
} else {
step = -step;
while (step>0) {
headB = headB.next;
step--;
}
}
while (headA!=headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
本文标题:LinkedList:两个单链表,返回第一个相交点,假设2个单链
本文链接:https://www.haomeiwen.com/subject/dprwrttx.html
网友评论