# Algorithm to create a singly linked list

I have an algorithm that should create a singly linked list from a textbook. It barely touched on any examples, so I would need some help figuring it out (still new to C.)

Essentially, the algorithm runs as follows:

``````Algorithm: CREATE (HEAD, ITEM)
1. [Create NEW node]
a) Allocate memory for NEW node.
b) IF NEW = NULL then Print: “Memory not Available” and Return
c) Set NEW→DATA = ITEM
3. Else
b) While Temp→LINK ≠ NULL do
[End of while]
[End of IF]
4. Return
``````

Here is what I have tried so far, but I could not understand the arrow mappings in the algorithm. Are these existing `C` features?

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

typedef struct node {
int DATA;
} node_t;

node_t* new =  NULL;
new = (node_t *)malloc(5*sizeof(node_t));
if(new == NULL){
prtinf("Memory not available");
return -1;
}
}
``````

### >Solution :

The arrow operator (`->`) in the algorithm is used to access a member of a struct using a pointer to that struct. It is equivalent to using the dot operator (.) to access a member of a struct, but with the added step of dereferencing the pointer to the struct. For example, if `p` is a pointer to a `struct node`, then `p->DATA` is equivalent to `(*p).DATA`.

In your code, you are using the `node_t` typedef to define the `struct node` type. This means that you can use `node_t *` to refer to a pointer to a `struct node`, and you can use `node_t->DATA` to access the `DATA` member of a `struct node` pointed to by `node_t`.

It looks like you are trying to implement the first step of the algorithm, which is to allocate memory for the new node and store the `ITEM` value in the `DATA` member of the node. You are using `malloc` to allocate memory for the new node, but you need to initialize the `DATA` member and the `LINK` member of the node. You can do this by using the arrow operator to access the members of the node:

``````node_t *create(int head, int item){
node_t* new =  NULL;
new = (node_t *)malloc(sizeof(node_t));
if(new == NULL){
printf("Memory not available");
return -1;
}

new->DATA = item;  // Set the DATA member of the new node
new->LINK = NULL;  // Set the LINK member of the new node to NULL
}

``````

You also need to return the new node from the `create` function so that you can use it later in the algorithm.

``````node_t *create(int head, int item){
node_t* new =  NULL;
new = (node_t *)malloc(sizeof(node_t));
if(new == NULL){
printf("Memory not available");
return -1;
}

new->DATA = item;  // Set the DATA member of the new node
new->LINK = NULL;  // Set the LINK member of the new node to NULL

return new;  // Return the new node
}

``````

You can then use the `create` function to create a new node and store it in a local variable in your main program. This will allow you to continue implementing the rest of the algorithm.

``````int main() {