剑指Offer——面试题52:两个链表的第一个公共结点

面试题52:两个链表的第一个公共结点
题目:输入两个链表,找出它们的第一个公共结点。
在这里插入图片描述

解决思路:

方法一:利用栈的特性,分别把两个链表的节点放入两个栈里,这样两个链表的尾节点就位于两个栈的栈顶,接下来比较两个栈顶的节点是否相同。如果相同,则把栈顶弹出接着比较下一个栈顶,直到找到最后一个相同的节点。
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
using namespace std;
struct ListNode{
	int value;
	ListNode* next;
};
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2){
	if(pHead1==NULL || pHead2==NULL) return NULL;
	stack<ListNode*> stack1,stack2;
	while(pHead1!=NULL){
		stack1.push(pHead1);
		pHead1=pHead1->next;
	}
	while(pHead2!=NULL){
		stack2.push(pHead2);
		pHead2=pHead2->next;
	}
	ListNode* preNode=NULL;
	while(!stack1.empty() && !stack2.empty()){
		if((stack1.top()) == (stack2.top())){
			preNode=stack1.top();
			stack1.pop();
			stack2.pop();
		}else {
			break;
		}
	}
	return preNode;
}
int main() {
	return 0;
}
方法二:首先遍历两个链表得到它们的长度,就能知道哪个链表比较长,以及长的链表比短的链表多几个节点。在第二次遍历的时候,在较长的链表上先走若干步,接着同时在两个链表上遍历,找到的第一个相同的节点就是它们的第一个公共节点。
#include<iostream>
#include<algorithm>
#include<set>
#include<vector>
#include<cstring>
#include<stack>
#include<cmath>
using namespace std;
struct ListNode{
	int value;
	ListNode* next;
};
unsigned int GetListLength(ListNode* pHead){
	unsigned int nlength=0;
	ListNode* pNode=pHead;
	while(pNode!=NULL){
		nlength++;
		pNode=pNode->next; 
	}
	return nlength;
}
ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2){
	// 得到两个链表的长度
	unsigned int nLength1=GetListLength(pHead1);
	unsigned int nLength2=GetListLength(pHead2);
	int nLengthDif=nLength1-nLength2;
	
	ListNode* pListHeadLong=pHead1;
	ListNode* pListHeadShort=pHead2;
	if(nLength2>nLength1){
		pListHeadLong=pHead2;
		pListHeadShort=pHead1;
		nLengthDif=nLength2-nLength1;
	}
	
	// 先在长链表上走几步, 再同时在两个链表上遍历
	for(int i=0;i<nLengthDif;i++) pListHeadLong=pListHeadLong->next;
	
	while(pListHeadLong!=NULL && pListHeadShort!=NULL && pListHeadLong!=pListHeadShort){
		pListHeadLong=pListHeadLong->next;
		pListHeadShort=pListHeadShort->next;
	} 
	
	// 得到第一个公共节点
	ListNode* pFirstCommonNode=pListHeadLong;
	return pFirstCommonNode; 
	 
}
int main() {
	return 0;
}
发布了74 篇原创文章 · 获赞 76 · 访问量 4056

猜你喜欢

转载自blog.csdn.net/qq_35340189/article/details/104474274
今日推荐