输入两个链表,找出它们的第一个公共结点。
/*
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 len1=getlength(pHead1);
int len2=getlength(pHead2);
int len3=len1-len2;
while(len3>0)
{
pHead1=pHead1.next;
len3--;
}
while(len3<0)
{
pHead2=pHead2.next;
len3++;
}
while(pHead1!=pHead2)
{
pHead1=pHead1.next;
pHead2=pHead2.next;
}
return pHead1;
}
int getlength(ListNode root)
{
int count=0;
while(root!=null)
{
count++;
root=root.next;
}
return count;
}
}