#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
Functions for the Linked List Insertions
struct node * insertAtFirst(struct node *head, int data){
struct node * ptr = (struct node *)malloc(sizeof(struct node));
ptr -> next = head;
ptr -> data = data;
return ptr;
}
struct node * insertAtEnd(struct node *head, int data){
struct node * ptr = (struct node *)malloc(sizeof(struct node));
ptr -> data = data;
struct node *p = head;
while (p -> next != NULL){
p = p -> next;
}
p -> next = ptr;
ptr -> next = NULL;
return head;
}
struct node * insertAtIndex(struct node *head, int data, int index){
struct node * ptr = (struct node *)malloc(sizeof(struct node));
struct node * p = head;
int i = 0;
while (i != index-1){
p = p -> next;
i++;
}
ptr -> data = data;
ptr -> next = p -> next;
p -> next = ptr;
return head;
}
// inserting a node after a certain perticular node.
struct node * insertAfter(struct node * head,struct node *prevNode, int data){
struct node * ptr = (struct node*) malloc(sizeof(struct node));
ptr -> data = data;
ptr -> next = prevNode -> next;
prevNode -> next = ptr;
return head;
}
now the main function ()
int main(){
// node * xyx (xyz is a Pointer variable)
struct node * head;
struct node * second;
struct node * third;
struct node * fourth;
//allocate memory for nodes 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 nodes '->' arrow operator
head -> data = 1;
head -> next = second;
second -> data = 2;
second -> next = third;
third -> data = 3;
third -> next = fourth;
//this is how to take input for a linked list node
//printf("Enter the element for 4th node : ");
//scanf("%d", &fourth -> data);
fourth -> data = 4;
fourth -> next = NULL;
printf("Linked list before insertion \\n");
linkedlistTraversal(head);
// uncomment the function call that you wanna use in this program
//head = insertAtFirst(head, 10);
//head = insertAtIndex(head, 20, 2);
//head = insertAtEnd(head, 30);
//head = insertAfter(head, third, 40);//node will be inserted after third node.
printf("Linked list after insertion at the end: \\n");
linkedlistTraversal(head);
return 0;
}
Compile all the snippets together to make it a fully functional working program.