0

Is anyone able to explain to me this function as mentioned in the walkthrough?

sllnode* create(VAL val)

I know it's a user defined function, and I have researched several pages of singly linked lists online but none refer to a function like this. I'm struggling to understand Doug's explanation in the walkthrough.

Any help greatly appreciated, cheers

2

Around 7:30 of the short, it is explained what it does.

A possible implementation might look like

typedef struct sllnode {
    VAL val;
    struct sllnode* next;
} sslnode

sllnode* create(VAL val)
{
    // allocate new node
    sllnode* new_node = malloc(sizeof(sllnode));

    // only if allocation was successful, initialise fields
    if (new_node != NULL)
    {
        new_node -> val = val;
        new_node -> next = NULL;
    }

    // return the pointer to the new node
    return new_node;
}

And yes, VAL was called VALUE minutes earlier :D

The returned node could be seen as a new linked list of exactly one element.

I found Nick Parlante's PDF http://cslibrary.stanford.edu/103/LinkedListBasics.pdf quite nice.

24
  • thanks so much for your reply. In my googling yesterday I found a couple of articles that dynamically allocate the memory of the node pointers slightly differently to what you and the pdf have got: – povoctober Jan 11 '19 at 14:41
  • struct Node* head = (struct Node*)malloc(sizeof(struct Node)); instead of sslnode* new_node = malloc(sizeof(sslnode)); I've noticed that the first type of malloc-ing (with the extra struct Node* before malloc) are included within int main(), whereas your own and the pdf's don't include int main(). Is this just a coincidence or is there a reason behind this? ... – povoctober Jan 11 '19 at 14:53
  • Also, when Doug talks about sslnode* new = create(6) Is that the 'head' pointer (as Nick refers to it) that sits on the stack? Would it sit outside the function of sllnode* create(VAL val)? Apologies for all the questions, I'm sincerely trying to understand. – povoctober Jan 11 '19 at 14:53
  • struct Node and sslnode can be considered the same (the sslnode itself is a typedef of struct sslnode, this typedef being a common pattern for structs). The explicit typecast of the pointer returned by malloc can be added to express intent, but does not change code at all. main is just another function with special usage. You cannot define functions within other functions, so those would be outside, but you cannot have code outside of functions, so actually calling those functions has to go somewhere. Not sure what you meant by mentioning main. – Blauelf Jan 11 '19 at 14:59
  • okay, thanks. where would sslnode* new = create(6) fit into your code from above? – povoctober Jan 11 '19 at 16:12

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .