题目描述
输入两个链表,找出它们的第一个公共结点。
解法参照《剑指offer》
/*
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;
int left=getLength(pHead1);
int right=getLength(pHead2);
int diff=left-right;
if(diff>0){
while(diff>0){
pHead1=pHead1.next;
diff--;
}
}else if(diff<0){
int len=-diff;
while(len>0){
pHead2=pHead2.next;
len--;
}
}
while(pHead1!=null&&pHead2!=null&&pHead1!=pHead2){
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return pHead1;
}
int getLength(ListNode head){
int count=0;
while(head!=null){
head=head.next;
count++;
}
return count;
}
}