首页 > 解决方案 > 这是递归的正确应用吗?(显示堆栈的项目)

问题描述

#include <stdio.h>
#include <stdlib.h>


struct node{
    int value;
    struct node *nextPtr;
};

typedef struct node Node;


void display(Node *head);
void push(Node **top, int newvalue);

int main(){

    Node *topPtr = NULL;

    push (&topPtr, 123);     // test with 123

    display(topPtr);

}

void display(Node *head){
    if (head == NULL){
        printf("\n");
        return;
    } else {
        printf("\n%d", head->value);    //
        display(head->nextPtr);         // is this recursion?
    }
}

void push(Node **top, int newvalue){
    Node *newlinkPtr = calloc(1,sizeof(Node));

    if(newlinkPtr){
        newlinkPtr->value = newvalue;
        newlinkPtr->nextPtr = *top;
        *top = newlinkPtr;
    } else {
        printf("\nNo memory.\n");
    }
}

display()函数是正确的递归应用程序吗?我有这个疑问,因为通常我在 printf 中进行递归调用,但这次不是。还是递归吗?如果不是,有没有办法在 printf 中做所有事情?

标签: cfunctionrecursionstack

解决方案


没有“正确应用递归”之类的东西。只要您通过合理使用计算和内存资源获得所需的结果,任何实现都应该没问题。

对于上面的特定情况,是的,看起来您已经正确实现了递归,它会给您一个具有合理时间复杂度的结果。


推荐阅读