Initialization of Linked List
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node * next;
};
Functions for the Operations
void linkedlistTraversal(struct node *ptr){
while (ptr != NULL){
//prints the element of the linked lists
printf("Element: %d \\n", ptr -> data);
ptr = ptr -> next;
}
}
//node insertion at the head of the Linked List.
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;
}
//insertion in the desired index.
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;
}
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;
}
// 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;
}
Driver Code
int main(){
int choice;
// 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 '->' assign operator
head -> data = 1;
head -> next = second;
second -> data = 2;
second -> next = third;
third -> data = 3;
third -> next = fourth;
fourth -> data = 4;
fourth -> next = NULL;
MENU
printf("MENU FOR LINKED LIST INSERTION OPERATIONS: \\n");
printf("Choose from the given options : \\n");
printf("1. Print the existing Linked List. \\n");
printf("2. Insertion at the start.\\n");
printf("3. Insertion at an index or in between. \\n");
printf("4. Insertion after a Node. \\n");
printf("5. Insertion at the very end of the linked list. \\n");
printf("6. Exit.\\n");
printf("Enter your choice : \\n");
scanf("%d", &choice);
switch (choice){
case 1:
linkedlistTraversal(head);
break;
case 2:
head = insertAtFirst(head, 10);
linkedlistTraversal(head);
break;
case 3:
head = insertAtIndex(head, 20, 2);
linkedlistTraversal(head);
break;
case 4:
head = insertAfter(head, third, 40);
linkedlistTraversal(head);
break;
case 5:
head = insertAtEnd(head, 30);
linkedlistTraversal(head);
break;
case 6:
break;
}
return 0;
}