/*Circular Singly linked list ka Insertion, Traversal, Searching, Deletion(Start, at any position, End) */
/*ka program hai */
//Deletion mein sabse jyada sochna pada hai normal linked list mein problem nahi hui Q dekh lena ek bar
/*Deletion mein agar position 1 ke liye alag block of code likhe hai else mein yani (last_position -1) positions ke liye alag (last_position) ke liye alag iss liye hoga qki (last_position -1) mein hame tail jo ki first circular list ko point kar raha hai use update nahi karn padta tha agar ham le bhi lenge uss code ko last position ke liye toh tail fir bhi wahi point karega jaha wo pehle kar raha tha yani deleted last node ko*/
/*last position deletion mein jo pointer position -1 place par hoga use tail banana hoga*/
#include<stdio.h>
#include<stdlib.h>
struct node {
int data;
struct node* next;
};
void add(struct node** tail, int val) {
struct node* temp = malloc(sizeof(struct node));
if(*tail == NULL) {
temp->data = val;
temp->next = temp;
*tail = temp;
} else {
temp->data = val;
temp->next = (*tail)->next;
(*tail)->next = temp;
}
}
void disp(struct node* tail) {
if(tail == NULL)
printf("NULL");
else {
struct node* p = tail->next;
do {
printf("<-%d", p->data);
p = p->next;
}while(p!=tail->next);
}
}
int search(struct node* tail, int val) {
if(tail == NULL){
printf("list is empty");
} else {
struct node* p = tail->next;
do {
if(p->data == val){
return 1;
break;
}
else {
p = p->next;
}
} while(p!=tail->next);
return -1;
}
}
void deleteNode(struct node** tail, int position) {
struct node* p = (*tail)->next;
struct node* temp ;
struct node* previous ;
if(*tail == NULL) {
printf("NULL");
}
else if(position == 1) {
(*tail)->next = p->next; //Updating tails next to next node
free(p);
p = NULL;
}else {
int num_of_nodes = 0;
do {
num_of_nodes++;
p = p->next;
} while(p != (*tail)->next);
printf("\nnumber of nodes = %d", num_of_nodes);
if(position == num_of_nodes) {
printf("\nnumber of nodes == position");
int i;
for(i = 1; i<=(position-1); i++) {
previous = p;
p = p->next;
}
temp = p;
previous->next = p->next;
*tail = previous;
free(temp);
temp = NULL;
} else {
printf("\nnumber of nodes != position");
int i;
for(i = 1; i<=(position-1); i++) {
previous = p;
p = p->next;
}
temp = p;
previous->next = p->next;
free(temp);
temp = NULL;
}
}
}
int main() {
int search_val = 4;
int del_pos = 3;
struct node* tail = NULL;
add(&tail, 1);
add(&tail, 2);
add(&tail, 3);
add(&tail, 4);
add(&tail, 5);
add(&tail, 6);
disp(tail);
int x = search(tail, search_val);
if(x==1) {
printf("\nsearch result found");
} else {
printf("\nsearch result not found");
}
deleteNode(&tail, 5);
printf("\n");
disp(tail);
return 0;
}
No comments:
Post a Comment