思路
较长的链表先进行遍历至两个链表的长度一致,注意考虑链表为空的时候。
从链表的定义可知,若两个单向链表有公共结点,那从某一结点开始,两个链表的next均指向同一个值。
公共结点:第一个值相同且next指向相同的结点。
/*
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) //有链表为空时返回null
return null;
int l1= Nlength(pHead1);
int l2= Nlength(pHead2);
ListNode p1= pHead1;
ListNode p2= pHead2;
int dis= l1-l2;
if (l1< l2){
p1= pHead2;
p2= pHead1;
dis= l2-l1;
}
for(int i=0;i< dis; i++){
p1=p1.next;
}
while ((p1 != null)&&(p2!= null)&&(p1!= p2))
{
p1= p1.next;
p2= p2.next;
}
ListNode pp = p1;
return pp;
}
//}
private int Nlength(ListNode head){
int length = 0;
ListNode l= head;
while(l.next != null){
length ++;
l= l.next;
}
return length;
}
}
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2){
int l1= Nlength(pHead1);
int l2= Nlength(pHead2);
ListNode p1= pHead1;
ListNode p2= pHead2;
int dis= l1-l2;
if (l1< l2){
p1= pHead2;
p2= pHead1;
dis= l2-l1;
}
for(int i=0;i< dis; i++){
p1=p1.next;
}
while ((p1.next != null)&&(p2.next != null)&&(p1.next != p2.next))
{
p1= p1.next;
p2= p2.next;
}
ListNode pp = p1;
return pp;
}
//}
private int Nlength(ListNode head){
int length = 0;
ListNode l= head;
while(l.next != null){
length ++;
l= l.next;
}
return length;
}
}