#include <bits/stdc++.h>
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
int getCount(ListNode *pHead)
{
int count = 0;
while (pHead)
{
count++;
pHead = pHead->next;
}
return count;
}
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2)
{
if (!pHead1 || !pHead2)
{
return nullptr;
}
int listCnt1 = getCount(pHead1);
int listCnt2 = getCount(pHead2);
int step = listCnt1 - listCnt2;
if (step > 0)
{
while (step)
{
pHead1 = pHead1->next;
step--;
}
}
else
{
int nStep = abs(step);
while (nStep)
{
pHead2 = pHead2->next;
nStep--;
}
}
while(pHead1 && pHead2)
{
if(pHead1 == pHead2)
{
return pHead1;
}
else
{
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
}
return nullptr;
}
};
int main()
{
ListNode* pHead1 = new ListNode(1);
pHead1->next = new ListNode(2);
pHead1->next->next = new ListNode(3);
ListNode* pHead2 = new ListNode(2);
pHead2->next = new ListNode(3);
Solution cSolution;
cSolution.FindFirstCommonNode(pHead1, pHead2);
return 1;
}
package main
import "math"
type ListNode struct {
Val int
Next *ListNode
}
func getCount(pHead *ListNode) int {
nCnt := 0
for pHead != nil {
nCnt++
pHead = pHead.Next
}
return nCnt
}
func FindFirstCommonNode(pHead1 *ListNode, pHead2 *ListNode) *ListNode {
if pHead1 == nil || pHead2 == nil {
return nil
}
list1 := getCount(pHead1)
list2 := getCount(pHead2)
step := list1 - list2
if step > 0 {
for step > 0 {
step--
pHead1 = pHead1.Next
}
} else {
nStep := math.Abs(float64(step))
for nStep > 0 {
nStep--
pHead2 = pHead2.Next
}
}
for pHead1 != nil && pHead2 != nil {
if pHead1 == pHead2 {
return pHead1
} else {
pHead1 = pHead1.Next
pHead2 = pHead2.Next
}
}
return nil
}