首先给出正常的查找方式:
LNode *LocateElem(LinkList L, ElemType e)
{
//本算法查找单链表 L (带头结点)中数据域值等于e的结点指针,否则返回NULL
LNode *p = L->next;
while (p != NULL && p->data != e) //从第1个结点开始查找data域为e的结点
p = p->next;
return p; //找到后返回该结点指针,否则返回NULL
}
下面给出错误的递归的方式:
Node* Find(Node* pHead, int data)
{
if (pHead)
{
Find(pHead->next, data);
if (pHead->_data == data)
return pHead;
//此处如果这样写找到了还是按照原来的步骤进行返回,等于没找到
}
return NULL;
}
下面给出正确的递归方式:
Node* Find(Node* pHead, int data)
{
if (pHead)
{
Node*res = Find(pHead->next, data);
if (res)
return res;
else
{
if (pHead->_data == data)
return pHead;
}
}
return NULL;
}