#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void link_list_Traversal_print(struct Node *ptr)
{
while (ptr != NULL)
{
printf("Element : %d\n", ptr->data);
ptr = ptr->next;
}
}
struct Node *insertAtFirst(struct Node *head, int data)
{ // Case : 1 : Insertion at the first
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)
{ // Case : 2 : Insertion at the end
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
struct Node *p = head;
while (p->next != NULL)
{
p = p->next;
}
ptr->data = data;
p->next = ptr;
ptr->next = NULL;
return head;
}
struct Node *insertAtIndex(struct Node *head, int data, int index)
{ // Case : 3 : insertion at any 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;
}
struct Node *insertAtNode(struct Node *head, struct Node *prevNode, int data)
{ // Case : 4 : insertion at a given Node
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
ptr->data = data;
ptr->next = prevNode->next;
prevNode->next = ptr;
return head;
}
int main()
{
struct Node *head;
struct Node *secoond;
struct Node *third;
struct Node *fourth;
struct Node *fifth;
head = (struct Node *)malloc(sizeof(struct Node));
secoond = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
fifth = (struct Node *)malloc(sizeof(struct Node));
head->data = 11;
head->next = secoond;
secoond->data = 85;
secoond->next = third;
third->data = 63;
third->next = fourth;
fourth->data = 25;
fourth->next = fifth;
fifth->data = 45;
fifth->next = NULL;
printf("Before Insertion : \n");
link_list_Traversal_print(head);
printf("\nAfter Insertion : \n");
// head = insertAtFirst(head,55);
// insertAtIndex(head,21,3);
// insertAtEnd(head,21);
insertAtNode(head, third, 10);
link_list_Traversal_print(head);
return 0;
}

0 Comments