两个链表的第一个公共结点

题目描述

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

方法一:先获取两个链表的长度,让较短的链表先走几步,然后同步遍历两个链表,使得这两个链表能够同时到达公共节点或者同时到达两个链表的末尾

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(pHead1 == nullptr || pHead2 == nullptr)
            return nullptr;
        
        int List1Len = 0;
        int List2Len = 0;
        
        ListNode* pNode1 = pHead1;
        ListNode* pNode2 = pHead2;
        
        //链表1的长度
        while(pNode1 != nullptr){
            List1Len++;
            pNode1 = pNode1->next;
        }
        
        //链表2的长度
        while(pNode2 != nullptr){
            List2Len++;
            pNode2 = pNode2->next;
        }
        
        //pNode1,pNode2回到起点
        pNode1 = pHead1;
        pNode2 = pHead2;
        
        if(List1Len > List2Len){
            for (int i = 0; i < List1Len - List2Len; i++)
                pNode1 = pNode1->next;
        }
        else if(List1Len < List2Len){
            for(int i = 0; i < List2Len - List1Len; i++)
                pNode2 = pNode2->next;
        }
        
        while(pNode1 != nullptr && pNode2 != nullptr && pNode1 != pNode2){
            pNode1 = pNode1->next;
            pNode2 = pNode2->next;
        }
        
        //没有公共节点
        if(pNode1 == nullptr)
            return nullptr;
        
        return pNode1;
        
    }
};

方法二:使用辅助栈,遍历两个链表,将其压入栈中,随后从链表尾节点开始同时出栈,即从尾节点开始同时向前遍历,直到找到最后一个公共节点

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
   
 //使用辅助栈
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(pHead1 == nullptr || pHead2 == nullptr)
            return nullptr;
        
        vector<ListNode*> stack1;
        vector<ListNode*> stack2;
        
        ListNode* pNode1 = pHead1;
        ListNode* pNode2 = pHead2;
        
        while(pNode1 != nullptr){
            stack1.push_back(pNode1);
            pNode1 = pNode1->next;
        }
        
        while(pNode2 != nullptr){
            stack2.push_back(pNode2);
            pNode2 = pNode2->next;
        }
        
        //两链表如果最后一个节点都不是公共节点,返回nullptr
        if(stack1[stack1.size() - 1] != stack2[stack2.size() - 1])
            return nullptr;
        
        ListNode* tmp = stack1[stack1.size() - 1];
        
        while(!stack1.empty() && !stack2.empty() && stack1[stack1.size() - 1] == stack2[stack2.size() - 1]){
            tmp = stack1[stack1.size() - 1];
            stack1.pop_back();
            stack2.pop_back();
        }
        
        return tmp;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值