首页 > 解决方案 > 我不知道它是如何工作的?

问题描述

开始指向以下链表的第一个节点的以下函数的输出是什么?

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); 
} 

标签: cdata-structureslinked-list

解决方案


作为一名新的贡献者,我将让您休息一下,并提供创建链接列表的代码,以及 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");
}

推荐阅读