题目描述
输入两个链表,找出它们的第一个公共结点。
public class 两个链表的第一个公共节点 {
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1==null||pHead2==null) {
return null;
}
int len1 = Getlength(pHead1);
int len2 = Getlength(pHead2);
ListNode shortnode,longnode;
int morelength = Math.abs(len1-len2);
if (len1>len2) {
longnode = pHead1;
shortnode = pHead2;
}else {
longnode = pHead2;
shortnode = pHead1;
}
for (int i = 0; i < morelength; i++) {
longnode = longnode.next;
}
while (longnode!=null&&shortnode!=null) {
if (longnode!=shortnode) {
longnode=longnode.next;
shortnode=shortnode.next;
}else {
return longnode;
}
}
return null;
}
private int Getlength(ListNode pHead1) {
// TODO Auto-generated method stub
int length = 0;
while (pHead1!=null) {
length++;
pHead1=pHead1.next;
}
return length;
}
}