Data Structures Lab
Circular Linked list
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};
void insert();
void display();
void delete();
typedef struct node DATA_NODE;
DATA_NODE *head_node = NULL, *tail_node = NULL, *temp_node = NULL;
int data;
int main() {
int option = 0;
printf("Circular Linked List - Insert, Delete, Display\n");
while (option < 4) {
printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("Others : Exit()\n");
printf("Enter your option: ");
scanf("%d", &option);
switch (option) {
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
default:
break;
}
}
return 0;
}
void insert() {
printf("\nEnter Element to Insert into Linked List: ");
scanf("%d", &data);
temp_node = (DATA_NODE *) malloc(sizeof(DATA_NODE));
temp_node->value = data;
if (head_node == NULL) {
head_node = temp_node;
tail_node = temp_node;
temp_node->next = head_node; // Point to itself, circular nature
} else {
tail_node->next = temp_node;
temp_node->next = head_node; // New node points to the head node
tail_node = temp_node; // Update the tail to the new node
}
printf("Inserted %d into the linked list.\n", data);
}
void delete() {
int pos, i = 1;
DATA_NODE *prev_node;
printf("Deleted the element at position %d.\n", pos);
if (head_node == NULL) { } else {
printf("List is empty, nothing to delete.\n"); temp_node = head_node;
return; while (i < pos && temp_node->next != head_node) {
} prev_node = temp_node;
temp_node = temp_node->next;
i++;
printf("\nEnter Position to Delete Element: "); }
scanf("%d", &pos); if (temp_node->next == head_node && i < pos) {
printf("Invalid position!\n");
if (pos == 1) { } else {
if (head_node == tail_node) { // Only one element in prev_node->next = temp_node->next;
the list if (temp_node == tail_node) {
tail_node = prev_node;
free(head_node);
}
head_node = tail_node = NULL; free(temp_node);
} else { printf("Deleted the element at position %d.\n", pos);
temp_node = head_node; }
head_node = head_node->next; }
tail_node->next = head_node; }
free(temp_node);
}
// Display the circular linked list
void display() {
if (head_node == NULL) {
printf("List is empty.\n");
return;
}
printf("\nDisplay Linked List: \n");
temp_node = head_node;
do {
printf("# %d # ", temp_node->value);
temp_node = temp_node->next;
} while (temp_node != head_node);
printf("\n");
}
Thank You