Create Linked List

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

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

void addNode(struct node** head_ref, int input)
{
 //1 create temp node
 struct node* temp = (struct node*)malloc(sizeof(struct node));
 
 //2 assign data to temp node
 temp->data = input;
 
 //3 temp node address should point to head_ref
 temp->next = (*head_ref);
 
 //4 move the head_ref to temp node
 (*head_ref) = temp;
 
}

void printNode(struct node* head)
{
 if(head == NULL) 
 {
 return;
 }
 
 printf("Data: %d , Next: %p \n", head->data, head->next);
 printNode(head->next);
};

int main()
{
 struct node* head = NULL;
 for(int i = 0; i < 5; i++)
 {
 addNode(&head, i);
 }
 
 printNode(head);
 
 return 0;
};
Advertisements