求两个链表的第一个公共结点,注意是单链表,一个结点相同,后面结点都相同
思路:两个链表第一个公共结点之后的结点都相同,较长的结点先走,走到两个链表相同长度时,
同时走,当两链表结点相同时,即为公共结点
另一种思路:链表尾部相同,从尾部走,最后一个相同的结点,即为所求结点
思路:两个链表第一个公共结点之后的结点都相同,较长的结点先走,走到两个链表相同长度时,
同时走,当两链表结点相同时,即为公共结点
另一种思路:链表尾部相同,从尾部走,最后一个相同的结点,即为所求结点
所以就要用到栈了。
上代码:
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
int length1 = GetLength(pHead1);
int length2 = GetLength(pHead2);
int res = length1-length2;
if(res < 0)
res = length2-length1;
ListNode *plong = length1>length2?pHead1:pHead2;
ListNode *pshort = length1>length2?pHead2:pHead1;
for(int i=0;i<res;++i)
plong = plong->next;
while(plong != NULL && pshort != NULL && plong != pshort)
{
plong = plong->next;
pshort = pshort->next;
}
ListNode *pFirstCommon = plong;
return pFirstCommon;
}
//计算链表长度
int GetLength(ListNode *pHead)
{
ListNode *p = pHead;
int length = 0;
while(p != NULL)
{
length++;
p = p->next;
}
return length;
}
};