简体   繁体   中英

I don't know how it works?

What is the output of following function for start pointing to first node of following linked list?

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

As a fellow new contributor, I'm going to give you a break and provide the code to create a linked list, and the one modification Blaze suggested. I'm not overly swift at C, so there are probably better implementations. Hope this will help you and/or others.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM