剑指offer:面试题37——两个链表的第一个公共节点
题目:输入两个链表,找出它们的第一个公共结点
思路:两个链表有公共节点,且都是单向链表,这意味着,从公共节点之后,两者节点都是相同的(即为Y型),因此两个链表指向的节点地址和值应该相同,但由于连个链表指针不同,因此判断时候如果借助栈,不能用指针判断,但是可以用top1==top2进行判断。
另一种方法是,分别遍历两个链表求出它们的长度差值,先在最长的链表上遍历找到直到两个链表长度相同的位置,然后同时遍历两个链表,比较它们的节点是否相同,直到找到共同节点
下面是用栈实现的代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
stack <ListNode*> s1;
stack <ListNode*> s2;
if(pHead1==NULL||pHead2==NULL)return nullptr;
while(pHead1!=NULL)
{
s1.push(pHead1);
pHead1=pHead1->next;
}
while(pHead2!=NULL)
{
s2.push(pHead2);
pHead2=pHead2->next;
}
ListNode *ret=NULL;
while(!s1.empty()&&!s2.empty()
&&s1.top()==s2.top()
)
{
s1.pop();
ret = s2.top();
s2.pop();
}
return ret;
}
};