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

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

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

/*
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;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值