题目描述
输入两个链表,找出它们的第一个公共结点。
解题思路:如果两个链表有公共节点,那么这两个链表从某一节点开始,它们的next都指向同一个节点,之后它们所有的节点都是重合的,不可能再出现分叉。所以拓扑形状看起来是Y型。
首先遍历两个链表得到它们的长度,比较链表的长度,以及长的链表比短的链表多几个节点。在第二次遍历的时候,先在较长的节点上走若干步,接着同时在两个链表上遍历,找到的第一个相同的节点就是它们的公共的节点。
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
int len1 = getLenOfList(pHead1);
int len2 = getLenOfList(pHead2);
int difLen = Math.abs(len1 - len2);
// 先在长链表上走几步,再同时在两个链表上遍历。
ListNode p1 = pHead1;
ListNode p2 = pHead2;
if (len1 > len2) {
for (int i = 0; i < difLen; i++) {
p1 = p1.next;
}
} else {
for (int i = 0; i < difLen; i++) {
p2 = p2.next;
}
}
while (p1 != null && p2 != null && p1 != p2) {
p1 = p1.next;
p2 = p2.next;
}
return p1;
}
public static int getLenOfList(ListNode head) {
int count = 0;
ListNode p = head;
while (p != null) {
count++;
p = p.next;
}
return count;
}