题目:输入两个链表,找出它们的第一个公共结点。
思路1:获取两个链表长度,算出差值,即为长链表先走的步数;走完这一部分,两个链表一起到相同结点时返回即可
代码1:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1==null||pHead2==null){
return null;
}
int len1=getLength(pHead1);
int len2=getLength(pHead2);
int diffLen=len1-len2;
ListNode pFirst=pHead1;
ListNode pNext=pHead2;
if(diffLen<0){
pFirst=pHead2;
pNext=pHead1;
diffLen=-diffLen;
}
for(int i=0;i<diffLen;i++){
pFirst=pFirst.next;
}
while(pFirst!=null&&pNext!=null&&(pFirst!=pNext)){
pFirst=pFirst.next;
pNext=pNext.next;
}
return pFirst;
}
public int getLength(ListNode head){
ListNode cur=head;
int len=0;
while(cur!=null){
len++;
cur=cur.next;
}
return len;
}
}
思路2 :遍历两次链表,第一次获取长度差值,第二遍得到公共结点;当两个链表长度相同时,一遍即可得到结果。
代码2:
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
while(p1!=p2){
p1 = ((p1==null) ? pHead2 : (p1=p1.next));
p2 = ((p2==null) ? pHead1 : (p2=p2.next));
}
return p1;
}