52 wins the Offer-- face questions: a first common node of the two lists

52 is inscribed: two lists a common node of the first
Title: two input lists, find their first common node.
Here Insert Picture Description

Solutions:

Method a: use of the characteristics of the stack, respectively, the two lists of nodes into two stacks, the two lists of such tail node on top of the stack of two stacks, the stack then compares the two nodes are the same. If so, put the top of the stack pop stack is then compared to the next, until you find the last one and the same node.
#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;
}
Method two: First, two lists obtained traverse their length, which can know the list is long, and a long list of multi-chain shorter than several nodes. When the second pass, and go over a long list of several steps, and then traversed simultaneously on two lists, the first one and the same node is found their first common node.
#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;
}
Published 74 original articles · won praise 76 · views 4056

Guess you like

Origin blog.csdn.net/qq_35340189/article/details/104474274