Below are separate codes for linked lists created using structure pointers and structure variables.
// Here a linked list is created using structure pointers
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * ptr;
};
void traversal(struct Node * poin)
{
while(poin != NULL)
{
printf("%d, ", poin->data);
poin = poin->ptr;
}
}
int main()
{
struct Node * head = NULL; // Structure pointers
struct Node * second = NULL;
struct Node * third = NULL;
head = (struct Node *) malloc (sizeof(struct Node));
second = (struct Node *) malloc (sizeof(struct Node));
third = (struct Node *) malloc (sizeof(struct Node));
head->data = 5;
head->ptr = second;
second->data = 23;
second->ptr = third;
third->data = 839;
third->ptr = NULL;
traversal(&head);
return 0;
}
// Here the same linked list is created using structure variables
#include <stdio.h>
struct Node
{
int data;
struct Node * ptr;
};
// Pointer poin moves along different elements of a linked list
void traversal(struct Node * poin)
{
while(poin != NULL)
{
printf("%d, ", poin->data);
poin = poin->ptr;
}
}
int main()
{
struct Node head, second, third; // Structure variables
head.data = 5;
head.ptr = &second;
second.data = 23;
second.ptr = &third;
third.data = 839;
third.ptr = NULL;
traversal(&head);
return 0;
}
Why linked lists are created using structure pointers while the same can be done using structure variables, if we ignore the dynamic memory allocation? It is still confusing to me.