简体   繁体   中英

Intersection of integer lists - unable to return the resultant list

I have written a code for the intersection of two linkedLists. I tried it on the Leetcode site and my code ran without any errors. I was trying out with a custom driver functions in main, and I don't receive the desired output.

Not sure where I'm going wrong. Can anyone pointout what I'm missing?

#include <iostream>
#include <string>
#include <cstring>

using namespace std;

struct ListNode {

int val;
ListNode *next;
ListNode(int x): val(x), next(NULL) {}
};

class Solution {
public:
    ListNode *getIntersection(ListNode *A, ListNode *B) {
        ListNode *p1 = A;
        ListNode *p2 = B;


        if(p1==NULL || p2==NULL)
            return NULL;

        while(p1!=NULL && p2!=NULL && p1!=p2) {
            p1=p1->next;
            p2=p2->next;

            if(p1==p2)
                return p1;

            if(p1==NULL) p1=B;
            if(p2==NULL) p2=A;    
        }

        return p1;
    }

    void print(ListNode *p) {
        while(p!=NULL) {
            cout<< p->val << " " ;
            p=p->next;  
        }

        cout<<endl;
    }
};

int main() {
    Solution s;
    ListNode *p1 = new ListNode(5);
    p1->next = new ListNode(11);

    s.print(p1);
    //similar for p2

    ListNode *p2 = new ListNode(6);
    p2->next = new ListNode(11);
    s.print(p2);

    s.getIntersection(p1,p2);
    return 0;
}

I think the main problem is that in the while loop you're comparing pointer-to-ListNode and not the value(s) contained in the ListNode :

while(p1!=NULL && p2!=NULL && **p1!=p2**) {
                              ^^^^^^^^^^^
                               here
    p1=p1->next;
    p2=p2->next;

    **if(p1==p2)**
    ^^^^^^^^^^^^^^
     and here
        return p1;

You should be doing:

while(p1!=NULL && p2!=NULL && p1->val!=p2->val) {
   ....

And then there is the problem that what you're computing might not be 'the intersection', but that's a different problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM