c - 这是递归的正确应用吗?(显示堆栈的项目)
问题描述
#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 中做所有事情?
解决方案
没有“正确应用递归”之类的东西。只要您通过合理使用计算和内存资源获得所需的结果,任何实现都应该没问题。
对于上面的特定情况,是的,看起来您已经正确实现了递归,它会给您一个具有合理时间复杂度的结果。
推荐阅读
- html - 在字段中输入文本时更改提交按钮的颜色
- vba - 如何用零值声明窗口
- jquery - jQuery ScrollTop 到元素 ID 在 Safari 上不起作用
- python-3.x - Flask-AppBuilder 等效于 SQLite WHERE 子句来过滤列数据
- ruby-on-rails - Ruby on Rails 保存模型 has_many 到 has_many 不会在构建时触发
- sql - SQL query to combine column data from multiple columns
- typescript - 基于动态(映射/条件)类型获取类型完成
- reference - CString::new().unwrap().as_ptr() 给出空 *const c_char
- c++ - 将 MFC Cimage 初始化为纯色
- c# - 更改精灵纹理像素会导致巨大的灰色正方形