[英]Intersection of integer lists - unable to return the resultant list
I have written a code for the intersection of two linkedLists. 我已经为两个linkedLists的交集编写了代码。 I tried it on the Leetcode site and my code ran without any errors. 我在Leetcode网站上进行了尝试,我的代码运行无任何错误。 I was trying out with a custom driver functions in main, and I don't receive the desired output. 我正在尝试使用main中的自定义驱动程序功能,但未收到所需的输出。
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循环中,您正在比较的是pointer-to-ListNode
而不是pointer-to-ListNode
包含的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. 然后是一个问题,您正在计算的可能不是“交集”,但这是一个不同的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.