递归实现单链表的查找

#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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值