两个链表的第一个公共节点(链表相交)

#题目描述
输入两个链表,找出它们的第一个公共结点

链表只要存在公共节点,那么公共节点后面所有的节点都是公共的。因此,对于这种一般两种思路
思路一:将两个链表分别压入两个栈中,然后从栈顶不断比较。知道遇到第一个不相等的节点,然后公共节点就是该节点的下一个节点
思路二:如果能将链表尾部对齐,那么就可以两两比较了,先分别获取两个链表的长度,然后分别获取两个链表的

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
#include<stack>
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        int length1=0;
        int length2=0;
        for(ListNode* p=pHead1;p!=NULL;p=p->next)//获得第一个链表的长度
            length1++;
        for(ListNode* p=pHead2;p!=NULL;p=p->next)//获得第二个链表的长度
            length2++;
		//下面是比较length,确定plong,pshort,dl
        ListNode* plong = pHead1;
        ListNode* pshort = pHead2;
        int dl=length1-length2;
        if(length1<length2){
            plong = pHead2;
            pshort = pHead1;
            dl=length2-length1;
        }
        //较长的先前进length步
        for(int i=0;i<dl;i++){
            plong=plong->next;
        }
        //然后,比较两个链表是否相同,不是则都继续前进
        while((plong!=NULL)&&(pshort!=NULL)&&(plong!=pshort)){
            plong=plong->next;
            pshort=pshort->next;
        }
        return plong;
    }
};

猜你喜欢

转载自blog.csdn.net/mr_ok1/article/details/88373365
今日推荐