#include <iostream>
using namespace std;
struct Node
{
Node(int data)
:_data(data)
,_next(NULL)
{}
Node* _next;
int _data;
};
Node* Find(Node* pHead, int data)
{
if(pHead == NULL)
{
return NULL;
}
else
{
Find(pHead->_next, data);
if(pHead->_data == data)//即使找到所需要找到的参数,但仍旧不会直接返回,还在继续递归调用,直到单链表结束,也不会找到结果
return pHead;
}
}
void FunTest()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
n1._next = &n2;
n2._next = &n3;
n3._next = &n4;
n4._next = &n5;
n5._next = NULL;
Node * ret = Find(&n1, 3);
cout<<ret<<endl;
}
int main()
{
FunTest();
system("pause");
return 0;
}
解决上述存在的问题:
#include <iostream>
using namespace std;
struct Node
{
Node(int data)
:_data(data)
,_next(NULL)
{}
Node* _next;
int _data;
};
Node* Find2(Node* pHead, int data)
{
if(pHead == NULL)
{
return NULL;
}
else
{
Node* pNode = Find2(pHead->_next, data);
if(pNode)
{
return pNode;
}
if(pHead->_data == data)
{
return pHead;
}
}
}
void FunTest()
{
Node n1(1);
Node n2(2);
Node n3(3);
Node n4(4);
Node n5(5);
n1._next = &n2;
n2._next = &n3;
n3._next = &n4;
n4._next = &n5;
n5._next = NULL;
Node * ret2 = Find2(&n1, 3);
cout<<ret2<<endl;
}
int main()
{
FunTest();
system("pause");
return 0;
}