c - 我不知道它是如何工作的?
问题描述
开始指向以下链表的第一个节点的以下函数的输出是什么?
1->2->3->4->5->6
void fun(struct node* start)
{
if(start == NULL)
return;
printf("%d ", start->data);
if(start->next != NULL )
fun(start->next->next);
printf("%d ", start->data);
}
解决方案
作为一名新的贡献者,我将让您休息一下,并提供创建链接列表的代码,以及 Blaze 建议的一个修改。我在 C 方面并不太快,所以可能有更好的实现。希望这会对您和/或其他人有所帮助。
#include "stdio.h"
#include "malloc.h"
struct node {
int data;
node* nextNode;
};
void fun(struct node* start)
{
printf("%d", start->data); // <=== this needs to be first
if (start->nextNode == NULL) {
return;
}
printf("->");
fun(start->nextNode);
}
node* findLastNode(struct node* previousNode)
{
if (previousNode->nextNode == NULL) {
return previousNode;
}
findLastNode(previousNode->nextNode);
}
void addNode(node* firstNode, int data)
{
node* lastNode = NULL;
node* nodePtr;
nodePtr = (node*)malloc(sizeof(node));
nodePtr->data = data;
nodePtr->nextNode = NULL;
if (firstNode->nextNode == NULL) {
firstNode->nextNode = nodePtr;
}
else {
lastNode = findLastNode(firstNode);
lastNode->nextNode = nodePtr;
}
}
int main()
{
node firstNode;
firstNode.nextNode = NULL;
addNode(&firstNode, 1);
addNode(&firstNode, 2);
addNode(&firstNode, 3);
addNode(&firstNode, 4);
addNode(&firstNode, 5);
addNode(&firstNode, 6);
fun(firstNode.nextNode);
printf("\n");
}
推荐阅读
- angular - 带有 Angular 和 Spring 错误的 Keycloak:GET http://localhost:8180/auth/realms/Storage/protocol/openid-connect/3p-cookies/step1.html 404(未找到)
- javascript - h3 点击事件(location.href)没有发生
- python - 如何从复杂(嵌套)的字典列表中创建数据框?
- datatables - Symfony Omines 数据表在表头中定义了一个 html
- css - 如何正确设置浮动标签的样式以不停留在输入字段的顶部?
- javascript - 尝试按照所有指南通过 Javascript 显示 html 代码,但没有显示任何内容
- ios - 为什么`NSLayoutConstraint.multiplier`是只读的?
- javascript - 如何检查数组中的单词是否有多个值
- python-3.x - Scrapy 在抓取表格时忽略格式化数据
- unity3d - 移动设备上的 Unity2D 对象旋转