Program : -
//C program for implementation of Linked List
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *head = NULL;
struct node *tail = NULL;
void insertAtHead(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = head;
if (head == NULL){
head = newNode;
tail = newNode;
}
else{
newNode->next = head;
head = newNode;
}
}
void insertAtTail(int data){
struct node *newNode = (struct node*)malloc(sizeof(struct node));
newNode->data = data;
newNode->next = NULL;
if (head==NULL){
head = newNode;
tail = newNode;
}
else {
tail->next = newNode;
tail = newNode;
}
}
void search(int num){
int count=0;
struct node *ptr = head;
if (head == NULL){
printf("List is empty hence no element found");
return;
}
while(ptr != NULL){
if (ptr->data == num){
count++;
}
ptr = ptr->next;
}
if (count == 1){
printf("Element is found!\n");
}
else {
printf("Element is not found!\n");
}
}
void deletion(int num){
int count=0;
struct node *ptr = head;
struct node *ptr2 = tail;
struct node *preptr;
if (head == NULL){
printf("List is empty hence no element found");
return;
}
if (ptr->data == num){
head = head->next;
return;
}
if (ptr2->data == num){
while(ptr->next != NULL){
preptr = ptr;
ptr = ptr->next;
}
preptr->next = NULL;
return;
}
while(ptr != tail){
if (ptr->next->data == num){
ptr->next = ptr->next->next;
return;
}
ptr = ptr->next;
}
}
void display(){
struct node *current = head;
if (head == NULL){
printf("Linked list is empty!\n");
return;
}
while(current != NULL){
printf("%d->", current->data);
current = current->next;
}
printf("NULL");
printf("\n");
}
int main(){
insertAtTail(7);
display();
insertAtHead(2);
display();
insertAtHead(1);
display();
insertAtTail(9);
display();
insertAtTail(45);
display();
return 0;
}
//Enjoy coding.....