51题两个链表的第一个公共节点

这是一篇关于解决数据结构问题的博客,主要探讨如何找出两个单链表的第一个公共节点。博主提出了两种方法,一种利用额外的存储空间,如stack或vector;另一种则不使用额外空间,通过调整较长链表的起始位置来实现。文章中包含详细的思路解析及代码实现。
摘要由CSDN通过智能技术生成

题目描述:

输入两个链表,找出它们的第一个公共结点。

思路:两种方法:

(1)借助外部空间stack或者vector

(2)不用外部空间,让较长的链表先走他们的长度差值步,然后一块走,找到相同的节点

代码:

class Solution {
public:
   ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
    if (pHead1 == nullptr || pHead2 == nullptr)return nullptr;
    vector<ListNode*>Vec1;
    vector<ListNode*>Vec2;
    ListNode*ptr_1 = pHead1;
    ListNode*ptr_2 = pHead2;
    while (ptr_1 != nullptr){
        Vec1.push_back(ptr_1);
        ptr_1 = ptr_1->next;
    }
    while (ptr_2 != nullptr){
        Vec2.push_back(ptr_2);
        ptr_2 = ptr_2->next;
    }
    if (*(Vec1.end()-1) != *(Vec2.end()-1))return nullptr;
    int n = Vec1.size() - 1;
    int m = Vec2.size() - 1;
    while (n >= 0 && m >= 0){
        if (Vec1[n] != Vec2[m])return Vec1[n+1];
        n--;
        m--;
    }
    if (n < 0)return pHead1;
    else
        return pHead2;
}
};
class Solution {
public:
  ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
	if (pHead1 == nullptr || pHead2 == nullptr)return nullptr;
	ListNode*ptr_1 = pHead1;
	ListNode*ptr_2 = pHead2;
	int n = 0;
	int m = 0;
	while (ptr_1 != nullptr){
		n++;
		ptr_1 = ptr_1->next;
	}
	while (ptr_2 != nullptr){
		m++;
		ptr_2 = ptr_2->next;
	}
	ptr_1 = pHead1;
	ptr_2 = pHead2;
	if (n >= m){
		int temp = n - m;
		while (temp > 0){
			ptr_1 = ptr_1->next;
			temp--;
		}
	}
	else{
		int temp = m - n;
		while (temp > 0){
			ptr_2 = ptr_2->next;
			temp--;
		}
	}
	while (ptr_1 != nullptr&&ptr_2 != nullptr){
		if (ptr_1 == ptr_2)return ptr_1;
		ptr_1 = ptr_1->next;
		ptr_2 = ptr_2->next;
	}
	return nullptr;
}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值