Description:输入两个链表,找出它们的第一个公共结点。
分析:因为是单链表,所以两个链表相交后,剩余的元素是相同的。
/*
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 = findLength(pHead1);
int len2 = findLength(pHead2);
if (len1 > len2) {
int cnt = len1 - len2;
while (cnt > 0) {
pHead1 = pHead1.next;
cnt--;
}
} else {
int cnt = len2 - len1;
while (cnt > 0) {
pHead2 = pHead2.next;
cnt--;
}
}
while (pHead1 != null) {
if (pHead1 == pHead2) return pHead1;
pHead1 = pHead1.next;
pHead2 = pHead2.next;
}
return null;
}
public int findLength(ListNode head) {
int count = 0;
while (head != null) {
count++;
head = head.next;
}
return count;
}
}