creation and traversal of Linked List DSA

amannarayanm · September 27, 2021 · C
#include <stdio.h>
#include<stdlib.h>

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

void linkedList_Traversal(struct node *ptr)
{
    while(ptr != NULL)
    {
        printf("%d ",ptr->data);
        ptr = ptr->next;
    }
}

int main() {
   
   struct node * head;
   struct node * second;
   struct node * third;
   struct node * fourth;
   
//   allocate the memory in heap

   head = (struct node *)malloc(sizeof(struct node));
   second = (struct node *)malloc(sizeof(struct node));
   third = (struct node *)malloc(sizeof(struct node));
   fourth = (struct node *)malloc(sizeof(struct node));
  
// link the nodes

    head->data = 12;
    head->next = second;
    second ->data = 14;
    second->next=third;
    third ->data = 16;
    third ->next = fourth;
    fourth ->data = 18;
    fourth->next = NULL;
   
   linkedList_Traversal(head);
   
    return 0;
}

Comments

Please sign up or log in to contribute to the discussion.