标签:
输入两个链表,找出它们的第一个公共结点。
/*
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;
}
ListNode headNode1 = pHead1;
ListNode headNode2 = pHead2;
int headLen1 = 0;
int headLen2 = 0;
while (headNode1 != null) {
headLen1++;
headNode1 = headNode1.next;
}
while (headNode2 != null) {
headLen2++;
headNode2 = headNode2.next;
}
headNode1 = pHead1;
headNode2 = pHead2;
int i = 0;
int cha = headLen1 - headLen2;
if (cha > 0) {
while (i < cha) {
headNode1 = headNode1.next;
i++;
}
} else {
while (i < -cha) {
headNode2 = headNode2.next;
i++;
}
}
while (headNode1 != null && headNode2 != null) {
if (headNode1 == headNode2) {
return headNode1;
}
headNode1 = headNode1.next;
headNode2 = headNode2.next;
}
return null;
}
}
标签:
原文地址:http://www.cnblogs.com/rosending/p/5656341.html