题目描述
输入两个链表,找出它们的第一个公共结点。
方法一:先获取两个链表的长度,让较短的链表先走几步,然后同步遍历两个链表,使得这两个链表能够同时到达公共节点或者同时到达两个链表的末尾
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == nullptr || pHead2 == nullptr)
return nullptr;
int List1Len = 0;
int List2Len = 0;
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
//链表1的长度
while(pNode1 != nullptr){
List1Len++;
pNode1 = pNode1->next;
}
//链表2的长度
while(pNode2 != nullptr){
List2Len++;
pNode2 = pNode2->next;
}
//pNode1,pNode2回到起点
pNode1 = pHead1;
pNode2 = pHead2;
if(List1Len > List2Len){
for (int i = 0; i < List1Len - List2Len; i++)
pNode1 = pNode1->next;
}
else if(List1Len < List2Len){
for(int i = 0; i < List2Len - List1Len; i++)
pNode2 = pNode2->next;
}
while(pNode1 != nullptr && pNode2 != nullptr && pNode1 != pNode2){
pNode1 = pNode1->next;
pNode2 = pNode2->next;
}
//没有公共节点
if(pNode1 == nullptr)
return nullptr;
return pNode1;
}
};
方法二:使用辅助栈,遍历两个链表,将其压入栈中,随后从链表尾节点开始同时出栈,即从尾节点开始同时向前遍历,直到找到最后一个公共节点
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
//使用辅助栈
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1 == nullptr || pHead2 == nullptr)
return nullptr;
vector<ListNode*> stack1;
vector<ListNode*> stack2;
ListNode* pNode1 = pHead1;
ListNode* pNode2 = pHead2;
while(pNode1 != nullptr){
stack1.push_back(pNode1);
pNode1 = pNode1->next;
}
while(pNode2 != nullptr){
stack2.push_back(pNode2);
pNode2 = pNode2->next;
}
//两链表如果最后一个节点都不是公共节点,返回nullptr
if(stack1[stack1.size() - 1] != stack2[stack2.size() - 1])
return nullptr;
ListNode* tmp = stack1[stack1.size() - 1];
while(!stack1.empty() && !stack2.empty() && stack1[stack1.size() - 1] == stack2[stack2.size() - 1]){
tmp = stack1[stack1.size() - 1];
stack1.pop_back();
stack2.pop_back();
}
return tmp;
}
};