Brushing notes (thirteen)-the first common node of two linked lists

Brushing notes (thirteen)-the first common node of two linked lists

Title description

Enter two linked lists to find their first common node. (Note that because the incoming data is a linked list, the error test data tips are displayed in other ways to ensure that the incoming data is correct)

Idea: If the two linked lists have a common node, then the nodes after the first common node are the same. So we can start from the end of the table and search for the first common node previously.

/*
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;
    }
};

 

Published 36 original articles · 19 praises · 20,000+ views

Guess you like

Origin blog.csdn.net/GJ_007/article/details/105469995