0

Is it even possible to create a singly linked list using a function outside of main and then access it once you leave the function?

pseudo:

#include //whatever needs to be included

function{
\\create and link lists in this function
}

main{
funtion()//call function to create lists and link properly

print(my_new_list)//traverse properly through the list here once out of function scope
}

I've been at this forever now and can't find any help out there to even confirm if it is possible this way or not. I understand how to build a linked list and then traverse it provided I am in the same function it was created in, it is the separate function that is messing things up for me because of the whole scope issue.

2
Contributors
1
Reply
6
Views
6 Years
Discussion Span
Last Post by Narue
0

Is it even possible to create a singly linked list using a function outside of main and then access it once you leave the function?

Um, yes. If that weren't possible, linked lists in C would be rather useless, no?

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

struct node {
    int data;
    struct node *next;
};

struct node *make_list(void)
{
    struct node *list = NULL;
    int i;
    
    for (i = 0; i < 10; i++) {
        struct node *nn = malloc(sizeof *nn);
        
        if (nn == NULL)
            break;
            
        nn->data = i;
        nn->next = list;
        list = nn;
    }
    
    return list;
}

int main(void)
{
    struct node *list = make_list();
    struct node *it, *save;
    
    for (it = list; it != NULL; it = save) {
        save = it->next;
        printf("%d\n", it->data);
        free(it);
    }
    
    return 0;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.