Insertion in Linked List

In this blog let us try to see how do we insert an element in the beginning of the list and also some other basic operations.

Let us understand it step by step:

Insertion at the beginning:

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

struct Node{
int data;
struct Node* next;
};
struct Node* insertatBeg(struct Node* head, int data){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data=data;

newNode->next=head;

head=newNode;

return head;
}

//let us try to understand this function 
-> is the arrow operator which we use to access the element in a list.

we first started with creating a node with insertatbeg name and going to declare the parameters which are head and data which is an integer in my case.

in the next line we are going to dynamically allocate memory it is going to be 8 because one is int which is 4 bytes and next pointer is 4 bytes.

the next line we are going to say that our newNode dot data is data itself in first and in the next line we are going to point our next pointer initially to the head and in the next line we are going to declare head to the newNode as it is our initial node.
and at last we are going to return to the head node. 
*/
void display(struct Node* head){
struct Node* current = head;
while(current!=NULL){
printf("%d -> ", current->data);
current = current->next;
}
printf("NULL\n");
}

/in this function we are going to declare the display function in which we passed the parameter head, now in the next line we are going to set a current pointer that is the present value to head node and then traverse the list upto last element and then when it is not null then print the present element and then point to the next element to the current element.
if not then print Null as it reached the last element.
int main(){
struct Node* head = NULL;
int data;

printf("Enter the data to insert: ");
scanf("%d ", &data);

head = insertatBeg(head, data); //recursion call insertatbeg

display(head);

return 0;
}
complete code

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

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

struct Node* insertatBeg(struct Node* head, int data){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data=data;

newNode->next=head;

head=newNode;

return head;

}

void display(struct Node* head){
struct Node* current = head;
while(current!=NULL){
printf("%d ->", current->data);
current = current->next;
}
printf("NULL\n");
}

int main(){
struct Node* head = NULL;
int data;
int n;

printf("Enter the number of elements to inserted ");
scanf("%d",&n);

for(int i = 0; i<n; i++){
printf("Enter the element to insert at %d position: ", i+1);
scanf("%d", &data);
head = insertatBeg(head,data);
}
display(head);

return 0;
}

Output:

Enter the number of elements to inserted 3
Enter the element to insert at 1 position: 1
Enter the element to insert at 2 position: 2
Enter the element to insert at 3 position: 3
3 ->2 ->1 ->NULL

Scroll to top