/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
//这是一个比较简单的题,首先,我们可以知道,单项链表要是有一个公共结点,则这两个链表的形式可以表示为一个‘Y’
//一开始的时候,我并没有考虑到两个链表的长度不同问题
//看了解析以及书上的思路,写出下面的代码
//链表的遍历还是比较简单的
//只不过就我自己而言,之前由于写了多项式的相乘相加时,中间出了一些问题导致现在对于链表遍历时要用当前这个节点还是要保存其后那个节点,有些晕晕的
//看来还是要多练习
class Solution {
public:
int GetLenofList(ListNode* pHead)
{
if(pHead==NULL)
return 0;
ListNode* tmp=pHead;
int count;
while(tmp!=NULL){
count++;
tmp = tmp->next;
}
return count;
}
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
//得到两个链表的长度
int len1=GetLenofList(pHead1);
int len2=GetLenofList(pHead2);
ListNode* firstCommonNode = NULL;
int diff = len1-len2;
ListNode* tmplong = pHead1;
ListNode* tmpshort = pHead2;
if(len2>len1){
diff = len2-len1;
tmplong = pHead2;
tmpshort = pHead1;
}
//长的链表多走几步
for(int i = 0; i<diff; i++)
tmplong = tmplong->next;
while(tmplong!=NULL&&tmpshort!=NULL){
if(tmplong==tmpshort){
firstCommonNode = tmplong;
break;
}
tmplong= tmplong->next;
tmpshort=tmpshort->next;
}
return firstCommonNode;
}
};
两个链表的第一个公共结点
最新推荐文章于 2024-10-23 22:52:14 发布