题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null) {
return null ;
}
ListNode p1 = pHead1 ;
ListNode p2 = pHead2 ;
int flag = 2 ;
while(p1 != null && p2 != null) {
if(p1 == p2) {//第一次相遇返回
return p1 ;
} else {
p1 = p1.next ;
p2 = p2.next ;
if(p1 == null) {
if(flag > 0){
p1 = pHead2 ;//p1第一次到达链尾,将pHead2拼在后面
flag-- ;//可拼接次数减一
}
}
if(p2 == null) {
if(flag > 0){
p2 = pHead1 ;//p2第一次到达链尾,将pHead1拼在后面
flag-- ;//可拼接次数减一
}
}
}
}
return null ;
}
}
一个菜鸟的算法刷题记录 文章被收录于专栏
分享一个菜鸟的成长记录
数字马力公司福利 22人发布
