Search code examples
clinked-listmallocnodes

C: setting up linked list using malloc()


I'm completely new to linked lists and have been give the below task:

"

Write a program that creates a Linked List of 10 int values (ranging from 1 to 10) using malloc().

" (There are further parts to this question but don't relate to what I'm stuck on)

I understand the concept of a linked list and I know how to use malloc(). However, the part I don't understand is nodes.

For example: how do you use malloc() on the nodes and the meaning of ->. If someone could explain how the nodes work to set up the linked list of 10 int values that would be great.


Solution

  • What you basically need to understand is that you need to create several nodes. Let's think about 4 nodes. Node A, B, C and D. So the use of malloc()is going to be to save in memory this 4 nodes (not in order, obviously).

    It is a linked list, not a sequential list. This means that you should be able to "access" it like you would normally do in a sequential list, but they are not sequentially saved in memory (hardware speaking).

    So: Your node A will have a pointer. This pointer will point to Node B. Same goes to Node B to node C, and Node C to Node D.

    A->B->C->D

    Remember ALL NODES must have whatever content you want, and a pointer to the next node, so you can access it from there.

    This means that Node A can be in (imagine), position 4 in memory, Node B in position 16 in memory, Node C in position 2 in memory, and node D in position 300 in memory.

    For example, an easy example using struct:

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

    When you insert a new node, you just need to change the pointers:

    A->B->C->D E (you want to insert it in the second position).

    So you need to change pointers. Something like:

     E=A->nextNode; //A is no longer pointing to B
    B=E->nextNode; //Now E is pointing to B
    

    To use malloc as you are asking:

    struct Node* A= malloc(sizeof(struct Node));   
      struct Node* B = malloc(sizeof(struct Node));  
    

    Take a look in here to see it better