#java
对 @一叶浮沉 代码思路的理解+分析
ps:第一眼看去差点没看明白 跑了下是对的 然后加入了些分析 希望对别人有帮助吧!
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
// 分析得 : 如果2个相加的链表,表头不相等 则肯定有共同尾部
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while (p1 != p2) {
p1 = p1.next;
p2 = p2.next;
// 寻找公共节点
if (p1 != p2) {
// 判断谁先走到了头 先走到头的回来继续走
// 相当于减去长链表比短链表长的部分 然后2个相同长度的链表从头开始遍历
// 时间复杂度为O(2n) 比我自己写的O(n^2)复杂度的代码好很多
if (p1 == null) {
p1 = pHead2;
}
if (p2 == null) {
p2 = pHead1;
}
}
}
return p1;
}下面是我的代码(相对好理解一些)
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
while(pHead1 != null){
ListNode node = pHead2;
while(node != null){
if(pHead1 == node){
return node;
}
node = node.next;
}
pHead1 = pHead1.next;
}
return null;
}


京公网安备 11010502036488号