#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node* link;
};
int main(){
int i,n,item;
struct node *head, *p, *q;
printf("enter the no. of nodes : ");
scanf("%d",&n);
printf("enter the head node : ");
scanf("%d",&item);
q = (struct node*)malloc(sizeof(struct node)); // so basically q is pointing towards a block(data + link) created from struct node
// the following statement is for the head node and we assume that its the only element of the list so its link(reference part) is NULL.
q->data = item;
q->link = NULL;
head = q; //now we make a head node and place the value of head value in it that was previously stored in q.
p = head; // we are directing p to head node.
// we would make a for loop to add other elements to the list and it would start with 1 as head node is created previously
for(i=1;i<n;i++)
{
printf("enter the next node : ");
scanf("%d",&item);
q = (struct node*)malloc(sizeof(struct node));
q->data = item;
q->link = NULL;
p->link = q;// we are linking the nodes as p is the head node and q is the new node we have created in the for loop.
p = p->link; // we are moving the pointer to the next node(next nodes address)
}
p = head;
printf("linked list : ");
//display all the nodes in the list
while(p->link != NULL) // for all the elements except last one as its link is NULL
{
printf("%d ", p->data); // print the data of each node
p = p->link; // move the pointer to the next node
}
if(p->link == NULL){ // for the last element in the linked list as its link in NULL.
printf("%d", p->data);
}
return 0;
}
0 Comments