/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#include <endian.h>
class Solution {
public:
//返回类型为 节点指针类型, 传入的是两个链表的头节点
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//先得到两个链表的长度,计算它俩的差x,让长的那个先走x步
//让后一起走,如果都走到最后还没有找到相同的,则这两个链表没有相同的节点
int length1 = GetLengethOfList(pHead1);
int length2 = GetLengethOfList(pHead2);
int x = 0;
if(length1 < length2)
{
x = length2 - length1;
for(int i = 0; i < x ; i++)
{
pHead2 = pHead2->next;
}
}
else {
x = length1 - length2;
for(int j = 0; j < x ; j++)
{
pHead1 = pHead1->next;
}
}
//两个链表走到相同的节点,或者两个节点都走到头
while(pHead1 && pHead2 && pHead1 != pHead2)
{
pHead1 = pHead1->next;
pHead2 = pHead2->next;
}
return pHead2;
}
int GetLengethOfList (ListNode* pHead)
{
int i = 0;
while(pHead)
{
i++;
pHead = pHead->next;
}
return i;
}
};
标签:ListNode,int,节点,链表,pHead1,pHead2,next,JZ52
From: https://www.cnblogs.com/H43724334/p/18131922