刷题笔记(十三)——两个链表的第一个公共节点

刷题笔记(十三)——两个链表的第一个公共节点

题目描述

输入两个链表,找出它们的第一个公共结点。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)

思路:若两个链表有公共节点,则从第一个公共节点开始后面节点相同。所以可以从表尾开始,先前查找第一个公共节点。

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
         ListNode *p, *q;
        p=pHead1;q=pHead2;
        if(p==NULL||q==NULL)
            return NULL;
        stack<ListNode*> s1;
    	stack<ListNode*> s2;
        while(p)
        {
            s1.push(p);
            p=p->next;
        }
        while(q)
        {
            s2.push(q);
            q=q->next;
        }
        ListNode *temp=NULL;
        while(!s1.empty()&&!s2.empty())
        {
            if(s1.top()==s2.top())
            {   temp=s1.top();
                s1.pop();
                s2.pop();
                
            }
            else
            {
                break;
            }
            
        }
        return temp;
    }
};
发布了36 篇原创文章 · 获赞 19 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/GJ_007/article/details/105469995
今日推荐